
正文
C#创建文件夹和文件
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
一、创建文件夹,例:
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
二、创建文件,例:
global::System.IO.FileInfo josnfile = new global::System.IO.FileInfo(JsonPath);
if (!josnfile.Exists)
{
// 创建map.json文件
FileStream fs = new FileStream(JsonPath, FileMode.CreateNew, FileAccess.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.Write("[]");
sw.Flush();
sw.Close();
//Thread.Sleep(300);
}
三、遍历文件夹下的所有文件或文件夹
遍历文件:
//录像文件
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())
{
}
}
四、读取文件内容,例:
using (FileStream fs = new FileStream(JsonPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs, Encoding.GetEncoding("gb2312")))
{
noteIsSubmit = sr.ReadToEnd().ToString().Contains(FileName);
}
}
五、复制文件,例:
global::System.IO.FileInfo _f = new global::System.IO.FileInfo(path);
try
{
if (!_f.Exists)
{
//复制讲稿文件
global::System.IO.FileInfo copyFile = new global::System.IO.FileInfo(FileURL);
copyFile.CopyTo(path);
}
}
catch (Exception ex)
{
Logger.D("NoteMake讲稿制作发生异常:", ex.Message);
}
六、删除指定文件,例:
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(, item.FilePath.LastIndexOf('.'));
if (Directory.Exists(noteFilePath))
{
DirectoryInfo _d = new DirectoryInfo(noteFilePath);
_d.Delete(true);//删除子目录和文件
}






