您的位置:首页 > 其它

文件读写

2016-05-11 18:53 169 查看
文件读写一直都是常用工具,但是也是经常出问题的地方,现总结一二

1. 创建文件

在库函数中有个File.create(filename)用于创建一个文件,但是如果没有对应Folder的情况下会抛异常System.IO.DirectoryNotFoundException,所以在每次新建文件是,最好创建Folder,

string subFolder = fileName.Substring(0, monitorFile.LastIndexOf(@"\"));
if (!Directory.Exists(subFolder))
{
Directory.CreateDirectory(subFolder);
}
File.Create(fileName);


2.创建文件在删除

下面是一段很无聊的代码,目的就是循环的创建文件,删除文件。但是下面的代码会报错:System.IO.IOException' in mscorlib.dll ("The process cannot access the file 'd:\a\b\c.txt' because it is being used by another process.")

while (true)
{
Console.WriteLine("create file...");
File.Create(fileName);
Console.WriteLine("Sleep 10 ms...");
Thread.Sleep(1000 * 10);
Console.WriteLine("delete file...");
File.Delete(fileName);
Console.WriteLine("Sleep 10 ms...");
Thread.Sleep(1000 * 10);
}
显示异常的地方是在delete的地方,为什么?可以看下Create函数的返回值就明白了,在create的时候同时打开了文件流,所以删除的时候就跑异常。故应先关闭流,或者直接使用using () { }语句。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: