![](/img/trans.png)
[英]The process cannot access the file 'D:.txt' because it is being used by another process in c#
[英]"The process cannot access the file --- because it is being used by another process" when making txt file C#
string path = @$"c:\Users\asmet\Desktop\Database1/{username}";
if (File.Exists(path) == false)
{
Console.WriteLine("Creating new file..");
File.Create(path);
// this is where the error is
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();
}
}
我是 C# 的超級新手,我真的不知道我在做什么,但每當我嘗試為安全的 rf、pf 和 sf 創建一個新文件時,它們都會崩潰。
這是在控制台應用程序的 VS Code 中。
用戶名來自早期代碼中的Console.ReadLine()
確切的錯誤信息:
System.IO.IOException:“進程無法訪問文件 'c:\Users\asmet\Desktop\Database1\ausernameientered',因為它正被另一個進程使用。”
DataBase1
只是一個文件夾
我試過查看與該問題相關的 forms,但經過一段時間的搜索后我從未找到解決方案,我希望代碼在指定的位置創建一個新文件,然后將值放入文本文檔,然后關閉它,所以我可以保存並稍后查看學校項目的數據。
發生的事情是每次我輸入“用戶名”並嘗試創建一個新文件后它都會崩潰。
如果你取出:
File.Create(path);
它可能會起作用。
StreamWriter(字符串,布爾值)
使用默認編碼和緩沖區大小為指定文件初始化 StreamWriter class 的新實例。 如果文件存在,它可以被覆蓋或追加。 如果該文件不存在,則此構造函數創建一個新文件。
File.Create 打開一個文件 stream。你應該切換
using (StreamWriter sw = new StreamWriter(path, true)) **// this is where the error is**
{
sw.WriteLine(DateTime.Now);
sw.WriteLine($"rf = {rf}");
sw.WriteLine($"pf = {pf}");
sw.WriteLine($"sf = {sf}");
sw.Close();
}
和
using (StreamWriter sw = File.Create(path)) **// this is where the error is**
{
sw.WriteLine(DateTime.Now);
sw.WriteLine($"rf = {rf}");
sw.WriteLine($"pf = {pf}");
sw.WriteLine($"sf = {sf}");
sw.Close();
}
您不能同時打開 2 個文件流。
您可以使用File.WriteAllLines
創建行並將行寫入文件。 根據文檔:
創建一個新文件,將一個或多個字符串寫入該文件,然后關閉該文件。 :
if (!File.Exists(path))
{
Console.WriteLine("Creating new file...");
File.WriteAllLines(path,
new[]
{
DateTime.Now.ToString(),
$"rf = {rf}",
$"pf = {pf}",
$"sf = {sf}"
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.