首页 > C风格编程语言 > C#编程资料 > C#中的文件操作大全(每贴更新5个)
2009
04-09

C#中的文件操作大全(每贴更新5个)

1.创建文件夹
Directory.CreateDirectory(%%1);


2.创建文件
File.Create(%%1);


3.删除文件
File.Delete(%%1);


4.删除文件夹
Directory.Delete(%%1);


5.删除一个文件下夹所有的文件夹
foreach (string dirStr in Directory.GetDirectories(%%1))
{
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;
Directory.Delete(%%1+”\\”+d.Name);
}
}
}


C#中的文件操作大全(每贴更新5个)》有 8 条评论

  1. hias_asia 说:

    6.清空文件夹
    Directory.Delete(%%1);
    Directory.CreateDirectory(%%1);

    7.读取文件
    StreamReader s = File.OpenText(%%1);
    string %%2 = null;
    while ((%%2 = s.ReadLine()) != null)
    {
    %%3
    }
    s.Close();

    8.写入文件
    FileInfo f = new FileInfo(%%1);
    StreamWriter w = f.CreateText();
    w.WriteLine(%%2);
    w.Close();

    9.写入随机文件
    //using System.IO;
            // Create random data to write to the file.
            byte[] dataArray = new byte[100000];//new Random().NextBytes(dataArray);
            using(FileStream 
    fileStream = new FileStream(%%1, 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.读取文件属性
    FileInfo f = new FileInfo(%%1);//f.CreationTime,f.FullName
    if((f.Attributes & FileAttributes.ReadOnly) != 0)
    {
    %%2
    }
    else
    {
    %%3
    }

  2. hias_asia 说:

    11.写入属性
    FileInfo f = new FileInfo(%%1);
    //设置只读
    f.Attributes = myFile.Attributes | FileAttributes.ReadOnly;
    //设置可写
    f.Attributes = myFile.Attributes & ~FileAttributes.ReadOnly;
    DirectoryInfo dir = new DirectoryInfo(%%1);
    FileInfo[] files = dir.GetFiles(“*.*”);
    foreach( FileInfo %%2 in files)
    {
    %%3
    }

    12.枚举一个文件夹中的所有文件夹
    foreach (string %%2 in Directory.GetDirectories(%%1))
    {
    %%3
    }

    13.复制文件夹
    DirectoryInfo dir = new DirectoryInfo(%%1);
    ArrayList folders=new ArrayList();
    FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
    folders.AddRange(fileArr);
    for (int i = 0; i < folders.Count; i++)
    {
        FileInfo f = folders[i] as FileInfo;
        if (f == null)
        {
            DirectoryInfo d = folders[i] as DirectoryInfo;
    Directory.CreateDirectory(%%2+”\\”+d.Name);
            folders.AddRange(d.GetFileSystemInfos());
    }
        else
    File.Copy(f.FullName,f.Directory.Name.Replace(%%1,%%2)+”\\”+f.Name);

    }

    14.复制一个文件夹下所有的文件夹到另一个文件夹下
    foreach (string dirStr in Directory.GetDirectories(%%1))
    {
    DirectoryInfo dir = new DirectoryInfo(dirStr);
    ArrayList folders=new ArrayList();
    FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
    folders.AddRange(fileArr);
    for (int i = 0; i < folders.Count; i++)
    {
        FileInfo f = folders[i] as FileInfo;
        if (f == null)
        {
            DirectoryInfo d = folders[i] as DirectoryInfo;
    Directory.CreateDirectory(%%2+”\\”+d.Name);
            folders.AddRange(d.GetFileSystemInfos());
    }
        else
    File.Copy(f.FullName,%%2+”\\”+f.Name);

    }
    }

    15.移动文件夹
    Directory.Move(%%1,%%2);

  3. hias_asia 说:

    15.移动一个文件夹下所有的文件夹到另一个目录下
    foreach (string dir in Directory.GetDirectories(%%1))
        Directory.Move(dir,%%2);

    16.以一个文件夹的框架在另一个目录创建文件夹和空文件
    DirectoryInfo dir = new DirectoryInfo(%%1);
    ArrayList folders=new ArrayList();
    FileSystemInfo[] fileArr = dir.GetFileSystemInfos();
    folders.AddRange(fileArr);
    for (int i = 0; i < folders.Count; i++)
    {
        FileInfo f = folders[i] as FileInfo;
        if (f == null)
        {
            DirectoryInfo d = folders[i] as DirectoryInfo;
    Directory.CreateDirectory(%%2+”\\”+d.Name);
            folders.AddRange(d.GetFileSystemInfos());
        }
        else
            File.Create(%%2+”\\”+f.Name);
    }

    17.复制文件
    File.Copy(%%1,%%2);

    18.复制一个文件夹下所有的文件到另一个目录
    foreach (string fileStr in Directory.GetFiles(%%1))
        File.Copy(%%1+”\\”+fileStr,%%2+”\\”+fileStr);

    19.提取扩展名
    %%2=Path.GetExtension(%%1);

    20.提取文件名
    %%2=File.GetName(%%1);

  4. hias_asia 说:

    21.提取文件路径
    %%2=File.GetParent(%%1);

    22.替换扩展名
    File.ChangeExtension(%%1,%%2);

    23.追加路径
    %%3=File.Combine(%%1,%%2);

    24.移动文件
    File.Move(%%1,%%2+”\\”+File.GetName(%%1));

    25.移动一个文件夹下所有文件到另一个目录
    foreach (string fileStr in Directory.GetFiles(%%1))
    File.Move(%%1+”\\”+fileStr,%%2+”\\”+fileStr);

  5. hias_asia 说:

    26.指定目录下搜索文件
    //using System.Text;
    //using System.IO;
    public   string   GetFile(string   fileName,string   dirName)  
      {  
      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   “找不到指定的文件”;  
       
      }

    27.打开对话框
    OpenFileDialog openFileDialog=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;
    %%1=fileOpen.ReadFile();
    %%1.AppendText(\”\”);
    }

    28.文件分割
    FileStream fsr = new FileStream(%%1, FileMode.Open, FileAccess.Read);
    byte[] btArr = new byte[fsr.Length];
    fsr.Read(btArr, 0, btArr.Length);
    fsr.Close();
    string strFileName=%%1.Substring(%%1.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();

    29.文件合并
    string strFileName = %%1.Substring(%%1.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();

    30.文件简单加密
    //读文件
    FileStream fsr = new FileStream(%%1, 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(%%1);
    FileStream fsw = new FileStream(%%2+”/” + “enc_” + strFileName, FileMode.Create, FileAccess.Write);
    fsw.Write(btArr, 0, btArr.Length);
    fsw.Close();

  6. hias_asia 说:

    31.文件简单解密
    FileStream fsr = new FileStream(%%1, 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;
        ibt %= 256;
        btArr[i] = Convert.ToByte(ibt);
    }
    //写文件
    string strFileName = Path.GetExtension(%%1);
    FileStream fsw = new FileStream(%%2 +”/” + strFileName, FileMode.Create, FileAccess.Write);
    fsw.Write(btArr, 0, btArr.Length);
    fsw.Close();

    32.读取ini文件属性
    //[DllImport("kernel32")]//返回0表示失败,非0为成功
    //private static extern long WritePrivateProfileString(string section,string key, string val,string filePath);
    //[DllImport("kernel32")]//返回取得字符串缓冲区的长度
    //private static extern long GetPrivateProfileString(string section,string key, string def,StringBuilder retVal,int size,string filePath);
    public static string ReadIniData(string Section,string Key,string NoText,string iniFilePath)
    {
        if(File.Exists(iniFilePath))
        {
    StringBuilder temp = new StringBuilder(1024);
    GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath);
    return temp.ToString();
        }
        else
        {
    return String.Empty;
        }
    }

    33.合并一个文件下所有的文件

    34.写入ini文件属性
    //[DllImport("kernel32")]//返回0表示失败,非0为成功
    //private static extern long WritePrivateProfileString(string section,string key, string val,string filePath);
    //[DllImport("kernel32")]//返回取得字符串缓冲区的长度
    //private static extern long GetPrivateProfileString(string section,string key, string def,StringBuilder retVal,int size,string filePath);
    public static bool WriteIniData(string Section,string Key,string Value,string iniFilePath)
    {
        if(File.Exists(iniFilePath))
        {
    long OpStation = WritePrivateProfileString(Section,Key,Value,iniFilePath);   
    if(OpStation == 0)
    {
        return false;
    }
    else
    {
        return true;
    }
        }
        else
        {
    return false;
        }
    }

    35.获得当前路径
    Environment.CurrentDirectory.ToString()

  7. hias_asia 说:

    36.读取XML数据库
    //using System.Xml;
    XmlDocument doc=new XmlDocument();
    doc.Load(%%1);
    CString %%9;
    XmlElement xe=doc.GetElementById(%%7);
    XmlNodeList elemList=xe.ChildNodes;
    foreach(XmlNode elem in elemList)
    {
    if(elem.NodeType==%%8)
    {
    %%9=elem.Value;
    break;
    }
    }

    37.写入XML数据库
    //using System.Xml;
    XmlDocument doc=new XmlDocument();
    doc.Load(%%1);
    XmlNode root=doc.DocumentElement;
    XmlElement book=doc.CreateElement(%%3);
    XmlElement book=doc.CreateElement(%%5);
    XmlElement port=doc.CreateElement(%%6);
    book.SetAttribute(%%4,root.ChildNodes.Count.ToString());
    author.InnerText=%%8;
    book.appendChild(author);
    book.appendChild(port);
    root.appendChild(book);
    doc.Save(%%1);

    38.ZIP压缩文件
    //using System.IO;
    //using System.IO.Compression;
    FileStream infile;
    try
    {
        // Open the file as a FileStream object.
        infile = new FileStream(%%1, FileMode.Open, FileAccess.Read, FileShare.Read);
        byte[] buffer = new byte[infile.Length];
        // Read the file to ensure it is readable.
        int count = infile.Read(buffer, 0, buffer.Length);
        if (count != buffer.Length)
        {
    infile.Close();
    //Test Failed: Unable to read data from file
    return;
        }
        infile.Close();
        MemoryStream ms = new MemoryStream();
        // Use the newly created memory stream for the compressed data.
        DeflateStream compressedzipStream = new DeflateStream(ms, CompressionMode.Compress, true);
        //Compression
        compressedzipStream.Write(buffer, 0, buffer.Length);
        // Close the stream.
        compressedzipStream.Close();
        //Original size: {0}, Compressed size: {1}”, buffer.Length, ms.Length);
    FileInfo f = new FileInfo(%%2);
    StreamWriter w = f.CreateText();
    w.Write(buffer,0,ms.Length);
    w.Close();
    } // end try
    catch (InvalidDataException)
    {
        //Error: The file being read contains invalid data.
    }
    catch (FileNotFoundException)
    {
        //Error:The file specified was not found.
    }
    catch (ArgumentException)
    {
        //Error: path is a zero-length string, contains only white space, or contains one or more invalid characters
    }
    catch (PathTooLongException)
    {
        //Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based

    platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
    }
    catch (DirectoryNotFoundException)
    {
        //Error: The specified path is invalid, such as being on an unmapped drive.
    }
    catch (IOException)
    {
        //Error: An I/O error occurred while opening the file.
    }
    catch (UnauthorizedAccessException)
    {
        //Error: path specified a file that is read-only, the path is a directory, or caller does not have the required

    permissions.
    }
    catch (IndexOutOfRangeException)
    {
        //Error: You must provide parameters for MyGZIP.
    }

    39.ZIP解压缩
    //using System.IO;
    //using System.IO.Compression;
    FileStream infile;
    try
    {
        // Open the file as a FileStream object.
        infile = new FileStream(%%1, FileMode.Open, FileAccess.Read, FileShare.Read);
        byte[] buffer = new byte[infile.Length];
        // Read the file to ensure it is readable.
        int count = infile.Read(buffer, 0, buffer.Length);
        if (count != buffer.Length)
        {
    infile.Close();
    //Test Failed: Unable to read data from file
    return;
        }
        infile.Close();
        MemoryStream ms = new MemoryStream();
        // ms.Position = 0;
        DeflateStream zipStream = new DeflateStream(ms, CompressionMode.Decompress);
        //Decompression
        byte[] decompressedBuffer = new byte[buffer.Length *2];
        zipStream.Close();
    FileInfo f = new FileInfo(%%2);
    StreamWriter w = f.CreateText();
    w.Write(decompressedBuffer);
    w.Close();
    } // end try
    catch (InvalidDataException)
    {
        //Error: The file being read contains invalid data.
    }
    catch (FileNotFoundException)
    {
        //Error:The file specified was not found.
    }
    catch (ArgumentException)
    {
        //Error: path is a zero-length string, contains only white space, or contains one or more invalid characters
    }
    catch (PathTooLongException)
    {
        //Error: The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based

    platforms, paths must be less than 248 characters, and file names must be less than 260 characters.
    }
    catch (DirectoryNotFoundException)
    {
        //Error: The specified path is invalid, such as being on an unmapped drive.
    }
    catch (IOException)
    {
        //Error: An I/O error occurred while opening the file.
    }
    catch (UnauthorizedAccessException)
    {
        //Error: path specified a file that is read-only, the path is a directory, or caller does not have the required

    permissions.
    }
    catch (IndexOutOfRangeException)
    {
        //Error: You must provide parameters for MyGZIP.
    }

    40.ZIP压缩文件夹
    //using System.IO;
    //using System.IO.Compression;
    ArrayList list = new ArrayList();
    foreach (string f in Directory.GetFiles(%%1))
    {
        byte[] destBuffer = File.ReadAllBytes(f);
        SerializeFileInfo sfi = new SerializeFileInfo(f, destBuffer);
        list.Add(sfi);
    }
    IFormatter formatter = new BinaryFormatter();
    using (Stream s = new MemoryStream())
    {
        formatter.Serialize(s, list);
        s.Position = 0;
        CreateCompressFile(s, %%2);
    }

  8. hiroki 说:

    正在开这项课程 应该看一看啊

留下一个回复