C#中文件创建与删除问题

来源:百度知道 编辑:UC知道 时间:2024/05/06 16:28:40
编译能通过,但是运行则出现异常,“文件“F:\VStest\file.txt”正由另一进程使用,因此该进程无法访问该文件。”
希望能给出错误原因及修改意见,谢谢。
static void Main(string[] args)
{
string filepath = @"F:\VStest\file.txt";

FileInfo myfile = new FileInfo(filepath);
myfile.Create();
myfile.Delete();
}

要先释放掉
static void Main(string[] args)
{
string filepath = @"F:\VStest\file.txt";

FileInfo myfile = new FileInfo(filepath);
if (!myfile.Exists)
{
FileStream fs = myfile.Create();
fs.Close();
}
myfile.Delete();
}

帮你测试过了。因为文件 已经存在,所以不用再创建了。使用如下的代码就能删除file.txt。
static void Main(string[] args)
{
string filepath = @"F:\VStest\file.txt";

FileInfo myfile = new FileInfo(filepath);
// myfile.Create(); 去掉创建方法,
myfile.Delete();
}