C# 文件與目錄的基本操作(System.IO)


1. 文件操作

image

/// <summary>
/// 文件讀寫操作
/// 為簡化代碼供大家學習,暫不考慮捕捉異常
/// </summary>
public partial class TestIO : DevComponents.DotNetBar.Office2007Form
{
    public TestIO()
    {
        InitializeComponent();
    }
 
    /// <summary>
    /// 創建文件
    /// </summary>
    private void btnCreateFile_Click(object sender, EventArgs e)
    {
        string path = Application.StartupPath + @"\Test.txt";
        FileStream fs = new FileStream(path, FileMode.Create);
        StreamWriter sw = new StreamWriter(fs);
        sw.WriteLine("This is a test file.");
        sw.WriteLine("This is second line.");
        sw.Close();
        fs.Close();
 
        // 也可以這樣創建 StreamWriter
        // StreamWriter sw = File.CreateText(path);
    }
 
    /// <summary>
    /// 讀取文件
    /// </summary>
    private void btnReadFile_Click(object sender, EventArgs e)
    {
        string path = Application.StartupPath + "\\Test.txt";
        textBoxX1.Text = string.Empty;
        if (File.Exists(path))
        {
            FileStream fs = new FileStream(path, FileMode.Open);
            StreamReader sr = new StreamReader(fs);
            // 也可以這樣創建 StreamReader
            // File.OpenText(path);
            string str = string.Empty;
            while (true)
            {
                str = sr.ReadLine();
                if (!string.IsNullOrEmpty(str))
                {
                    textBoxX1.Text += str + "\r\n";
                }
                else
                {
                    sr.Close();
                    fs.Close();
                    break;
                }
            }
        }
        else
        {
            MessageBox.Show("指定的路徑下不存在此文件!");
        }
    }
 
    /// <summary>
    /// 追加文件內容
    /// </summary>
    private void btnAppendFile_Click(object sender, EventArgs e)
    {
        string path = Application.StartupPath + "\\Test.txt";
        FileStream fs = new FileStream(path, FileMode.Append);
        StreamWriter sw = new StreamWriter(fs);
        // 也可以這樣創建 StreamReader
        // StreamWriter sw = File.AppendText(path);
        sw.WriteLine("This is three line.");
        sw.Close();
        fs.Close();
    }
 
    /// <summary>
    /// 復制文件
    /// </summary>
    private void btnCopyFile_Click(object sender, EventArgs e)
    {
        string oldPath = Application.StartupPath + "\\Test.txt";
        string newPath = Application.StartupPath + "\\TestClone.txt";
        File.Copy(oldPath, newPath);
    }
 
    /// <summary>
    /// 刪除文件
    /// </summary>
    private void btnDeleteFile_Click(object sender, EventArgs e)
    {
        string path = Application.StartupPath + "\\TestClone.txt";
        File.Delete(path);
    }
 
 
    /// <summary>
    /// 移動文件
    /// </summary>
    private void btnMoveFile_Click(object sender, EventArgs e)
    {
        string oldPath = Application.StartupPath + "\\Test.txt";
        // 移動文件的同時也可以使用新的文件名
        string newPath = "d:\\NewTest.txt";
        File.Move(oldPath, newPath);
    }
 
    /// <summary>
    /// 創建目錄
    /// </summary>
    private void btnCreateDirectory_Click(object sender, EventArgs e)
    {
        string path1 = "d:\\Jason1";
        // 創建目錄 Jason1
        DirectoryInfo dDepth1 = Directory.CreateDirectory(path1);
        // dDepth2 指向 dDepth1 創建的子目錄 Jason2
        DirectoryInfo dDepth2 = dDepth1.CreateSubdirectory("Jason2");
        // 設置應用程序當前的工作目錄為 dDepth2 指向的目錄
        Directory.SetCurrentDirectory(dDepth2.FullName);
        // 在當前目錄創建目錄 Jason3
        Directory.CreateDirectory("Jason3");
    }
 
    private void btnDeleteDirectory_Click(object sender, EventArgs e)
    {
        string path = "d:\\Jason1";
        DeleteDirectory(path);
    }
 
    /// <summary>
    /// 刪除目錄及其所有子目錄,文件
    /// </summary>
    private static void DeleteDirectory(string path)
    {
        if (Directory.Exists(path))
        {
            foreach (string str in Directory.GetFileSystemEntries(path))
            {
                if (File.Exists(str))
                {
                    File.Delete(str);
                }
                else
                {
                    DeleteDirectory(str);
                }
            }
            Directory.Delete(path);
        }
        else
        {
            MessageBox.Show("該目錄不存在!");
        }
    }
 
    private void btnCopyDirectory_Click(object sender, EventArgs e)
    {
        string sourcePath = "d:\\Jason1";
        string targetPath = "d:\\Jason2";
        CopyDirectory(sourcePath, targetPath);
    }
 
    /// <summary>
    /// 復制目錄及其所有內容
    /// </summary>
    /// <param name="sourcePath">源目錄</param>
    /// <param name="targetPath">目標目錄</param>
    private void CopyDirectory(string sourcePath, string targetPath)
    {
        // 該字符用於在反映分層文件系統組織的路徑字符串中分隔目錄級別(msdn)
        // 在windows系統下實質上是為目錄路徑加上"\\"
        if (targetPath[targetPath.Length - 1] != Path.DirectorySeparatorChar)
        {
            targetPath += Path.DirectorySeparatorChar;
        }
        // 目標目錄不存在則創建之
        if (!Directory.Exists(targetPath))
        {
            Directory.CreateDirectory(targetPath);
        }
        // 獲取文件系統(含目錄和文件)
        string[] fileList = Directory.GetFileSystemEntries(sourcePath);
        foreach (string fileName in fileList)
        {
            if (Directory.Exists(fileName))
            {
                // Path.GetFileName(fileName) 可取出最后一個分級目錄名或文件名
                CopyDirectory(fileName, targetPath + Path.GetFileName(fileName));
            }
            else
            {
                // true 為可覆蓋
                File.Copy(fileName, targetPath + Path.GetFileName(fileName), true);
            }
        }
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM