文件操作大全

本文详细介绍了在.NET框架下进行文件和文件夹操作的各种方法,包括创建、删除、复制、移动等常见操作步骤,并提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    1.创建文件夹
    //using System.IO;
    Directory.CreateDirectory(@path);

    2.创建文件
    //using System.IO;
    File.Create(@path);

    3.删除文件
    //using System.IO;
    File.Delete(@path);

    4.删除文件夹
    //using System.IO;
    Directory.Delete(@path);

    5.删除一个目录下所有的文件夹
    //using System.IO;
    foreach (string dirStr in Directory.GetDirectories(@path))
    {
     DirectoryInfo dir = new DirectoryInfo(dirStr);
     ArrayList folders=new ArrayList();
     FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
     for (int i = 0; i < folders.Count; i++)
     {
      FileInfo f = folders[i] as FileInfo;
      if (f == null)
      {
       DirectoryInfo d = folders[i] as DirectoryInfo;
       d.Delete();
      }
     }
    }

    6.清空文件夹
    //using System.IO;
    Directory.Delete(@path,true);
    Directory.CreateDirectory(@path);

    7.读取文件
    //using System.IO;
    StreamReader s = File.OpenText(@path);
    string %%2 = null;
    while ((%%2 = s.ReadLine()) != null){
     %%3
    }
    s.Close();

    8.写入文件
    //using System.IO;
    FileInfo f = new FileInfo(@path);
    StreamWriter w = f.CreateText();
    w.WriteLine(%%2);
    w.Close();

    9.写入随机文件
    //using System.IO;
    byte[] dataArray = new byte[100000];//new Random().NextBytes(dataArray);
    using(FileStream FileStream = new FileStream(@path, FileMode.Create)){
    // Write the data to the file, byte by byte.
     for(int i = 0; i < dataArray.Length; i++){
      FileStream.WriteByte(dataArray[i]);
     }
    // Set the stream position to the beginning of the file.
     FileStream.Seek(0, SeekOrigin.Begin);
    // Read and verify the data.
     for(int i = 0; i < FileStream.Length; i++){
      if(dataArray[i] != FileStream.ReadByte()){
       //写入数据错误
       return;
      }
     }
    //"数据流"+FileStream.Name+"已验证"
    }

    10.读取文件属性
    //using System.IO;
    FileInfo f = new FileInfo(@path);//f.CreationTime,f.FullName
    if((f.Attributes & FileAttributes.ReadOnly) != 0){
     %%2
    }
    else{
     %%3
    }

    11.写入属性
    //using System.IO;
    FileInfo f = new FileInfo(@path);
    //设置只读
    f.Attributes = myFile.Attributes | FileAttributes.ReadOnly;
    //设置可写
    f.Attributes = myFile.Attributes & ~FileAttributes.ReadOnly;

    12.枚举一个文件夹中的所有文件夹
    //using System.IO;
    foreach (string %%2 in Directory.GetDirectories(@path)){
     %%3
    }


    13.复制文件夹

    string path = (%%2.LastIndexOf("\") == %%2.Length - 1) ? %%2 : %%2+"\";
    string parent = Path.GetDirectoryName(@path);
    Directory.CreateDirectory(path + Path.GetFileName(@path));
    DirectoryInfo dir = new DirectoryInfo((@path.LastIndexOf("\") == @path.Length - 1) ? @path : @path + "\");
    FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
    Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());
    while (Folders.Count>0)
    {
                        FileSystemInfo tmp = Folders.Dequeue();
                        FileInfo f = tmp as FileInfo;
                        if (f == null)
                        {
                            DirectoryInfo d = tmp as DirectoryInfo;
                            Directory.CreateDirectory(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", path));
                            foreach (FileSystemInfo fi in d.GetFileSystemInfos())
                            {
                                Folders.Enqueue(fi);
                            }
                        }
                        else
                        {
                            f.CopyTo(f.FullName.Replace(parent, path));
                        }
    }

    14.复制目录下所有的文件夹到另一个文件夹下

    DirectoryInfo d = new DirectoryInfo(@path);
    foreach (DirectoryInfo dirs in d.GetDirectories())
    {
        Queue<FileSystemInfo> al = new Queue<FileSystemInfo>(dirs.GetFileSystemInfos());
        while (al.Count > 0)
        {
            FileSystemInfo temp = al.Dequeue();
            FileInfo file = temp as FileInfo;
            if (file == null)
            {
                DirectoryInfo directory = temp as DirectoryInfo;
                Directory.CreateDirectory(path + directory.Name);
                foreach (FileSystemInfo fsi in directory.GetFileSystemInfos())
                    al.Enqueue(fsi);
            }
            else
                File.Copy(file.FullName, path + file.Name);
        }
    }

    15.移动文件夹

                    string filename = Path.GetFileName(@path);
                    string path=(%%2.LastIndexOf("\") == %%2.Length - 1) ? %%2 : %%2 + "\";
                    if (Path.GetPathRoot(@path) == Path.GetPathRoot(%%2))
                        Directory.Move(@path, path + filename);
                    else
                    {
                        string parent = Path.GetDirectoryName(@path);
                        Directory.CreateDirectory(path + Path.GetFileName(@path));
                        DirectoryInfo dir = new DirectoryInfo((@path.LastIndexOf("\") == @path.Length - 1) ? @path : @path + "\");
                        FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
                        Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());
                        while (Folders.Count > 0)
                        {
                            FileSystemInfo tmp = Folders.Dequeue();
                            FileInfo f = tmp as FileInfo;
                            if (f == null)
                            {
                                DirectoryInfo d = tmp as DirectoryInfo;
                                DirectoryInfo dpath = new DirectoryInfo(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", path));
                                dpath.Create();
                                foreach (FileSystemInfo fi in d.GetFileSystemInfos())
                                {
                                    Folders.Enqueue(fi);
                                }
                            }
                            else
                            {
                                f.MoveTo(f.FullName.Replace(parent, path));
                            }
                        }
                        Directory.Delete(@path, true);
                    }

    16.移动目录下所有的文件夹到另一个目录下

    string filename = Path.GetFileName(@path);
                    if (Path.GetPathRoot(@path) == Path.GetPathRoot(%%2))
                        foreach (string dir in Directory.GetDirectories(@path))
                            Directory.Move(dir, Path.Combine(%%2,filename));
                    else
                    {
                        foreach (string dir2 in Directory.GetDirectories(@path))
                        {
                            string parent = Path.GetDirectoryName(dir2);
                            Directory.CreateDirectory(Path.Combine(%%2, Path.GetFileName(dir2)));
                            string dir = (dir2.LastIndexOf("\") == dir2.Length - 1) ? dir2 : dir2 + "\";
                            DirectoryInfo dirdir = new DirectoryInfo(dir);
                            FileSystemInfo[] fileArr = dirdir.GetFileSystemInfos();
                            Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dirdir.GetFileSystemInfos());
                            while (Folders.Count > 0)
                            {
                                FileSystemInfo tmp = Folders.Dequeue();
                                FileInfo f = tmp as FileInfo;
                                if (f == null)
                                {
                                    DirectoryInfo d = tmp as DirectoryInfo;
                                    DirectoryInfo dpath = new DirectoryInfo(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", %%2));
                                    dpath.Create();
                                    foreach (FileSystemInfo fi in d.GetFileSystemInfos())
                                    {
                                        Folders.Enqueue(fi);
                                    }
                                }
                                else
                                {
                                    f.MoveTo(f.FullName.Replace(parent, %%2));
                                }
                            }
                            dirdir.Delete(true);
                        }
                    }

    17.以一个文件夹的框架在另一个目录创建文件夹和空文件

    bool b=false;
    string path = (%%2.LastIndexOf("\") == %%2.Length - 1) ? %%2 : %%2 + "\";
    string parent = Path.GetDirectoryName(@path);
    Directory.CreateDirectory(path + Path.GetFileName(@path));
    DirectoryInfo dir = new DirectoryInfo((@path.LastIndexOf("\") == @path.Length - 1) ? @path : @path + "\");
    FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
    Queue<FileSystemInfo> Folders = new Queue<FileSystemInfo>(dir.GetFileSystemInfos());
    while (Folders.Count > 0)
    {
        FileSystemInfo tmp = Folders.Dequeue();
        FileInfo f = tmp as FileInfo;
        if (f == null)
        {
            DirectoryInfo d = tmp as DirectoryInfo;
            Directory.CreateDirectory(d.FullName.Replace((parent.LastIndexOf("\") == parent.Length - 1) ? parent : parent + "\", path));
            foreach (FileSystemInfo fi in d.GetFileSystemInfos())
            {
                Folders.Enqueue(fi);
            }
        }
        else
        {
            if(b) File.Create(f.FullName.Replace(parent, path));
        }
    }

    18.复制文件
    //using System.IO;
    File.Copy(@path,%%2);

    19.复制一个文件夹下所有的文件到另一个目录
    //using System.IO;
    foreach (string fileStr in Directory.GetFiles(@path))
     File.Copy((@path.LastIndexOf("\") == @path.Length - 1) ? @path +Path.GetFileName(fileStr): @path + "\"+Path.GetFileName(fileStr),(%%2.LastIndexOf("\\") == %%2.Length - 1) ? %%2 +Path.GetFileName(fileStr): %%2 + "\"+Path.GetFileName(fileStr));

    20.提取扩展名
    //using System.IO;
    string %%2=Path.GetExtension(@path);

    21.提取文件名
    //using System.IO;
    string %%2=Path.GetFileName(@path);

    22.提取文件路径
    //using System.IO;
    string %%2=Path.GetDirectoryName(@path);

    23.替换扩展名
    //using System.IO;
    File.ChangeExtension(@path,%%2);

    24.追加路径
    //using System.IO;
    string %%3=Path.Combine(@path,%%2);

    25.移动文件
    //using System.IO;
    File.Move(@path,%%2+"\"+file.getname(@path));

    26.移动一个文件夹下所有文件到另一个目录
    foreach (string fileStr in Directory.GetFiles(@path))
     File.Move((@path.LastIndexOf("\") == @path.Length - 1) ? @path +Path.GetFileName(fileStr): @path + "\"+Path.GetFileName(fileStr),(%%2.LastIndexOf("\\") == %%2.Length - 1) ? %%2 +Path.GetFileName(fileStr): %%2 + "\"+Path.GetFileName(fileStr));

    27.指定目录下搜索文件

    string fileName=@path;
    string dirName=%%2;
     DirectoryInfo   dirc=new   DirectoryInfo(dirName);
     foreach(FileInfo   file   in   dirc.GetFiles()) {
      if(file.Name.IndexOf(fileName)>-1)
       return file.FullName;
      }
      foreach(DirectoryInfo   dir   in   dirc.GetDirectories())   {
       return   GetFile(fileName,dir.FullName);
      }
      return   "找不到指定的文件";
     }

    28.打开对话框
    OpenFileDialog penFileDialog=new OpenFileDialog();
    openFileDialog.InitialDirectory="c:\\\\";//注意这里写路径时要用c:\\\\而不是c:\\
    openFileDialog.Filter="文本文件|*.*|C#文件|*.cs|所有文件|*.*";
    openFileDialog.RestoreDirectory=true;
    openFileDialog.FilterIndex=1;
    if (openFileDialog.ShowDialog()==DialogResult.OK) {
     fName=openFileDialog.FileName;
     File fileOpen=new File(fName);
     isFileHaveName=true;
     @path=fileOpen.ReadFile();
     @path.AppendText("");
    }

    29.文件分割
    //using System.IO;
    FileStream fsr = new FileStream(@path, FileMode.Open, FileAccess.Read);
    byte[] btArr = new byte[fsr.Length];
    fsr.Read(btArr, 0, btArr.Length);
    fsr.Close();
    string strFileName=@path.Substring(@path.LastIndexOf("\")+1);
    FileStream fsw = new FileStream(%%2 + strFileName + "1", FileMode.Create, FileAccess.Write);
    fsw.Write(btArr, 0, btArr.Length/2);
    fsw.Close();
    fsw = new FileStream(%%2 + strFileName + "2", FileMode.Create, FileAccess.Write);
    fsw.Write(btArr, btArr.Length/2, btArr.Length-btArr.Length/2);
    fsw.Close();

    30.文件合并
    //using System.IO;
    string strFileName = @path.Substring(@path.LastIndexOf("\") + 1);
    FileStream fsr1 = new FileStream(%%2 + strFileName + "1", FileMode.Open, FileAccess.Read);
    FileStream fsr2 = new FileStream(%%2 + strFileName + "2", FileMode.Open, FileAccess.Read);
    byte[] btArr = new byte[fsr1.Length+fsr2.Length];
    fsr1.Read(btArr, 0, Convert.ToInt32(fsr1.Length));
    fsr2.Read(btArr, Convert.ToInt32(fsr1.Length), Convert.ToInt32(fsr2.Length));
    fsr1.Close();fsr2.Close();
    FileStream fsw = new FileStream(%%2 + strFileName, FileMode.Create, FileAccess.Write);
    fsw.Write(btArr, 0, btArr.Length);
    fsw.Close();

    31.文件简单加密
    //using System.IO;
    //读文件
    FileStream fsr = new FileStream(@path, FileMode.Open, FileAccess.Read);
    byte[] btArr = new byte[fsr.Length];
    fsr.Read(btArr, 0, btArr.Length);
    fsr.Close();
    for (int i = 0; i < btArr.Length; i++){ //加密
     int ibt = btArr[i];
     ibt += 100;
     ibt %= 256;
     btArr[i] = Convert.ToByte(ibt);
    }
    //写文件
    string strFileName = Path.GetExtension(@path);
    FileStream fsw = new FileStream(%%2+"/" + "enc_" + strFileName, FileMode.Create, FileAccess.Write);
     fsw.Write(btArr, 0, btArr.Length);
     fsw.Close();

  
32.获得应用程序完整路径
    string @path=Application.ExecutablePath;
 
33.文本查找替换

            if (args.Length == 3)
            {
ReplaceFiles(args[0],args[1],args[2],null);
            }

            if (args.Length == 4)
            {
if (args[3].Contains("v"))
{
    ReplaceVariable(args[0], args[1], args[2], args[3]);
}
else
{
    ReplaceFiles(args[0], args[1], args[2], args[3]);
}
            }

        /// <summary>
        /// 替换环境变量中某个变量的文本值。可以是系统变量,用户变量,临时变量。替换时会覆盖原始值。小心使用
        /// </summary>
        /// <param name="variable"></param>
        /// <param name="search"></param>
        /// <param name="replace"></param>
        /// <param name="options"></param>
        public static void ReplaceVariable(string variable, string search, string replace, string options)
        {
string variable=@path;
 string search=%%2;
 string replace=%%3;
            string text=Environment.GetEnvironmentVariable(variable);
            System.Windows.Forms.MessageBox.Show(text);
            text=ReplaceText(text, search, replace, options);
            Environment.SetEnvironmentVariable(variable, text);
            text = Environment.GetEnvironmentVariable(variable);
            System.Windows.Forms.MessageBox.Show(text);
        }

 

        /// <summary>
        /// 批量替换文件文本
        /// </summary>
        /// <param name="args"></param>
        public static void ReplaceFiles(string path,string search, string replace, string options)
        {
string path=@path;
string search=%%2;
string replace=%%3;
            string[] fs;
            if(File.Exists(path)){
ReplaceFile(path, search, replace, options);
return;
            }
            if (Directory.Exists(path))
            {
fs = Directory.GetFiles(path);
foreach (string f in fs)
{

    ReplaceFile(f, search, replace, options);
}
return;
            }
            int i=path.LastIndexOf("");
            if(i<0)i=path.LastIndexOf("/");
            string d, searchfile;
            if (i > -1)
            {
d = path.Substring(0, i + 1);
searchfile = path.Substring(d.Length);
            }
            else
            {
d = System.Environment.CurrentDirectory;
searchfile = path;
            }

            searchfile = searchfile.Replace(".", @".");
            searchfile = searchfile.Replace("?", @"[^.]?");
            searchfile = searchfile.Replace("*", @"[^.]*");
            //System.Windows.Forms.MessageBox.Show(d);  System.Windows.Forms.MessageBox.Show(searchfile);
            if (!Directory.Exists(d)) return;
            fs = Directory.GetFiles(d);
            foreach (string f in fs)
            {
if(System.Text.RegularExpressions.Regex.IsMatch(f,searchfile))
    ReplaceFile(f, search, replace, options);
            }
        }
     
        /// <summary>
        /// 替换单个文本文件中的文本
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="search"></param>
        /// <param name="replace"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static bool ReplaceFile(string filename, string search, string replace,string options)
        {
string path=@path;
string search=%%2;
string replace=%%3;
            FileStream fs = File.OpenRead(filename);
            //判断文件是文本文件还二进制文件。该方法似乎不科学
            byte b;
            for (long i = 0; i < fs.Length; i++)
            {
b = (byte)fs.ReadByte();
if (b == 0)
{
    System.Windows.Forms.MessageBox.Show("非文本文件");
    return false;//有此字节则表示改文件不是文本文件。就不用替换了
}
            }
            //判断文本文件编码规则。
            byte[] bytes = new byte[2];
            Encoding coding=Encoding.Default;
            if (fs.Read(bytes, 0, 2) > 2)
            {
if (bytes == new byte[2] { 0xFF, 0xFE }) coding = Encoding.Unicode;
if (bytes == new byte[2] { 0xFE, 0xFF }) coding = Encoding.BigEndianUnicode;
if (bytes == new byte[2] { 0xEF, 0xBB }) coding = Encoding.UTF8;
            }
            fs.Close();
            //替换数据
            string text=File.ReadAllText(filename, coding);
            text=ReplaceText(text,search, replace, options);
            File.WriteAllText(filename, text, coding);
            return true;
        }
        /// <summary>
        /// 替换文本
        /// </summary>
        /// <param name="text"></param>
        /// <param name="search"></param>
        /// <param name="replace"></param>
        /// <param name="options"></param>
        /// <returns></returns>
        public static string ReplaceText(string text, string search, string replace, string options)
        {
            RegexOptions ps = RegexOptions.None;
            if (options == null)  //纯文本替换
            {
search = search.Replace(".", @".");
search = search.Replace("?", @"?");
search = search.Replace("*", @"*");
search = search.Replace("(", @"(");
search = search.Replace(")", @")");
search = search.Replace("[", @"[");
search = search.Replace("[", @"[");
search = search.Replace("[", @"[");
search = search.Replace("{", @"{");
search = search.Replace("}", @"}");
ops |= RegexOptions.IgnoreCase;
            }
            else
            {
if(options.Contains("I"))ops |= RegexOptions.IgnoreCase;
            }
            text = Regex.Replace(text, search, replace, ops);
            return text;
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值