C#创建文件夹和文件
生活随笔
收集整理的這篇文章主要介紹了
C#创建文件夹和文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一、創建文件夾,例:
1 if (!Directory.Exists(path))
2 {
3 Directory.CreateDirectory(path);
4 }
二、創建文件,例:
1 global::System.IO.FileInfo josnfile = new global::System.IO.FileInfo(JsonPath);
2 if (!josnfile.Exists)
3 {
4 // 創建map.json文件
5 FileStream fs = new FileStream(JsonPath, FileMode.CreateNew, FileAccess.ReadWrite);
6 StreamWriter sw = new StreamWriter(fs);
7 sw.Write("[]");
8 sw.Flush();
9 sw.Close();
10 //Thread.Sleep(300);
11 }
三、遍歷文件夾下的所有文件或文件夾
遍歷文件:
//錄像文件
string videoPath = fileManager.TrimEnd('\') + "\" + item.CourtID + "\Conference\" + item.ID;
if(Directory.Exists(videoPath))
{
DirectoryInfo TheFolder = new DirectoryInfo(videoPath);
//遍歷文件
foreach (global::System.IO.FileInfo NextFile in TheFolder.GetFiles())
{
}
}
遍歷文件夾:
if(Directory.Exists(videoPath))
{
DirectoryInfo TheFolder=new DirectoryInfo(videoPath);
//遍歷文件夾
foreach(DirectoryInfo NextFolder in TheFolder.GetDirectories())
{
}
}
四、讀取文件內容,例:
1 using (FileStream fs = new FileStream(JsonPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
2 {
3 using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312")))
4 {
5 noteIsSubmit = sr.ReadToEnd().ToString().Contains(FileName);
6 }
7 }
五、復制文件,例:
1 global::System.IO.FileInfo _f = new global::System.IO.FileInfo(path);
2 try
3 {
4 if (!_f.Exists)
5 {
6 //復制講稿文件
7 global::System.IO.FileInfo copyFile = new global::System.IO.FileInfo(FileURL);
8 copyFile.CopyTo(path);
9 }
11 }
12 catch (Exception ex)
13 {
14 Logger.D("NoteMake講稿制作發生異常:", ex.Message);
15 }
六、刪除指定文件,例:
string path = FileManager.BASEPATH + "\" + item.CourtID + "\Topics\" + item.ID + "\" + item.Type + ".doc";
global::System.IO.FileInfo _f = new global::System.IO.FileInfo(path);
if (_f.Exists)
{
global::System.IO.File.Delete(path);
}
七、刪除指定文件夾,例:
//講稿標注文檔路徑
string noteFilePath = item.FilePath.Substring(0, item.FilePath.LastIndexOf('.'));
if (Directory.Exists(noteFilePath))
{
DirectoryInfo _d = new DirectoryInfo(noteFilePath);
_d.Delete(true);//刪除子目錄和文件
}
總結
以上是生活随笔為你收集整理的C#创建文件夹和文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Polygon Cruncher减边用法
- 下一篇: OSG的垃圾回收机制