C#创建TXT文件报错:文件被另一进程占用问题求助
解决C#创建文件后写入时提示被占用的问题
你遇到的错误是因为调用File.Create(path)后,该方法返回的FileStream对象没有被关闭,导致文件当前被你的程序自己占用,后续StreamWriter无法打开写入。
方案1:直接使用StreamWriter创建并写入(推荐)
StreamWriter的构造函数在指定文件不存在时,会自动创建文件,不需要提前调用File.Create。修改代码如下:
string path = @$"c:\Users\asmet\Desktop\Database1/{username}"; if (!File.Exists(path)) { Console.WriteLine("Creating new file.."); // 直接用StreamWriter,文件不存在会自动创建,using块会自动关闭流 using (StreamWriter sw = new StreamWriter(path, true)) { sw.WriteLine(DateTime.Now); sw.WriteLine($"rf = {rf}"); sw.WriteLine($"pf = {pf}"); sw.WriteLine($"sf = {sf}"); // 不需要手动调用sw.Close(),using块结束时会自动释放资源 } }
注意:using语句块会自动处理StreamWriter的资源释放,包括关闭文件流,所以不需要手动调用sw.Close()。
方案2:正确处理File.Create返回的流
如果一定要保留File.Create的调用,需要关闭它返回的FileStream:
string path = @$"c:\Users\asmet\Desktop\Database1/{username}"; if (!File.Exists(path)) { Console.WriteLine("Creating new file.."); // 捕获File.Create返回的流,并关闭它 using (FileStream fs = File.Create(path)) { // 这里可以做一些文件创建后的操作,不需要的话直接空块即可 } using (StreamWriter sw = new StreamWriter(path, true)) { sw.WriteLine(DateTime.Now); sw.WriteLine($"rf = {rf}"); sw.WriteLine($"pf = {pf}"); sw.WriteLine($"sf = {sf}"); } }
额外提示
- 路径规范:C#中路径建议统一用
\(配合@符号避免转义),比如@$"c:\Users\asmet\Desktop\Database1\{username}",更符合Windows路径习惯。 - 文件夹检查:如果
Database1文件夹不存在,程序会抛出找不到路径的错误,建议提前判断并创建:
string folderPath = @"c:\Users\asmet\Desktop\Database1"; if (!Directory.Exists(folderPath)) { Directory.CreateDirectory(folderPath); }
内容的提问来源于stack exchange,提问作者nuqko
相关产品推荐
相关产品推荐

