C#-IO-正由另一进程使用,因此该进程无法访问该文件

mac2025-06-04  22

原代码如下:

static void Main(string[] args)         {             Directory.CreateDirectory(@"d:\ok");             File.Create(@"d:\ok\abc.txt");             string str = "sve";             FileStream fs = null;             try             {                 //1、创建文件流(字节流)                 using (fs = new FileStream(@"d:\ok\abc.txt", FileMode.OpenOrCreate, FileAccess.Write))                 {                     byte[] bytes = Encoding.Default.GetBytes(str);                     //2、写操作                     fs.Write(bytes, 0, bytes.Length);                                  fs.Flush();//清空流                     Console.WriteLine("写入成功!");                 }                          }             catch (Exception ex)             {                 Console.WriteLine(ex.Message);             }             finally             {                 //3、关闭流                 fs.Close();             }         }

上面执行会出错:文件“d:\ok\abc.txt”正由另一进程使用,因此该进程无法访问该文件

原因:File.Create(@"d:\ok\abc.txt");这句代码会返回一个FileStream流与该文件链接,因此被占用。

解决方法:将上面的代码改为File.Create(@"d:\ok\abc.txt").Close();即可解决

最新回复(0)