C#檔案目錄操作方法匯總_C#教程

來源:互聯網
上載者:User

需要 using System.IO;

1) 相對路徑轉絕對路徑

string fullfolder = HttpContext.Current.Server.MapPath(folder);

2) 檔案移動(改名)

File.Move(Server.MapPath("/a.txt"), Server.MapPath("/b.txt"));

3) 檔案複製

File.Copy(Server.MapPath("/a.txt"), Server.MapPath("/b.txt"), true);

4) 檔案是否存在

File.Exists(filefullname)

5) 目錄是否存在

Directory.Exists(fullfolder))

6) 建立目錄

Directory.CreateDirectory(fullfolder);

7) 目錄移動

Directory.Move

8) 讀取文字檔

StreamReader srd = File.OpenText(fullfilename);
srd.ReadToEnd();
srd.Close();
srd.Dispose();

9) 寫檔案

StreamWriter swr = File.CreateText(Server.MapPath("test.txt"));
swr.Write("message");
swr.Close();
swr.Dispose();

10)刪除檔案

// 刪除硬碟上的檔案
if (File.Exists(filefullname))
{
    File.Delete(filefullname);
}

11)目錄遍曆

public void ListFiles(string pathname)
{
    // 所有目錄與檔案
    string[] subDirs = Directory.GetDirectories(pathname);
    string[] subFiles = Directory.GetFiles(pathname);
    foreach (string subDir in subDirs)
    {
        ListFiles(subDir);
    }
    // 所有檔案
    foreach (string subFile in subFiles)
    {
        string filename = Path.GetFileName(subFile);
    }
}

12)檔案修改時間

FileInfo fi = new FileInfo(@"c:\test.txt");
DateTime writetime = fi.LastWriteTime;

13)從含路徑的檔案名稱中提取檔案名稱

System.IO.Path.GetFileName(fullPath);//檔案名稱

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.