當我調用該Generate函數時,它不會創建StreamWriter對象,而是拋出一個異常:另一個進程使用的文件但文件未打開,這是第一個使用它的流。 public static string GetWindowsUserName() { string st = System.Security.Principal.WindowsIdentity.GetCurrent().Name; bool Condition = false; foreach (char ch in st) { if (ch == '\\') Condition = true; } if (Condition) { string[] stArr = st.Split('\\'); st = stArr[stArr.Length - 1]; } return st; } public static void Generate(bool Desktop, bool RemoveLast, bool InExistingTxt, int Count, int Length) { Random Generator = new Random(); if (Desktop) path = $"C:\\Users\\{GetWindowsUserName()}\\Desktop\\GeneratedNumbers.txt"; else path = "GeneratedNumbers.txt"; if (!InExistingTxt && !RemoveLast) File.Create(path); else if (!InExistingTxt && RemoveLast) { if (File.Exists(path)) { File.Delete(path); } File.Create(path); } System.Threading.Thread.Sleep(1000); if (File.Exists(path)) { StreamWriter SW = new StreamWriter(path); for (int i = 0; i < Count; i++) { string st = ""; for (int j = 0; j < Length; j++) { int o = Generator.Next(0, 11); st += Convert.ToString(o); } SW.WriteLine(st); } SW.Dispose(); } }
1 回答

臨摹微笑
TA貢獻1982條經驗 獲得超2個贊
File.Create將流返回到創建的文件。由于您沒有處理流,因此在嘗試重新打開同一文件時會出錯。
我還懷疑您搞砸了“RemoveLast”邏輯。我假設您想要在現有文件設置為 false 時將內容附加到現有文件:
if (InExistingTxt && !File.Exists(path))
return;
StreamWriter SW;
if (RemoveLast)
SW = File.CreateText(path);
else
SW = File.AppendText(path);
using (SW)
{
for (int i = 0; i < Count; i++)
{
string st = "";
for (int j = 0; j < Length; j++)
{
int o = Generator.Next(0, 11);
st += Convert.ToString(o);
}
SW.WriteLine(st);
}
}
- 1 回答
- 0 關注
- 108 瀏覽
添加回答
舉報
0/150
提交
取消