我正在用 C# 制作控制臺(tái)應(yīng)用程序。我用一個(gè)Process.Start()函數(shù)打開一個(gè)文本文件,可以直接在記事本中編輯,程序等待記事本關(guān)閉。但是當(dāng)試圖保存文件時(shí),會(huì)彈出一條警告消息,提示“文件正在被另一個(gè)進(jìn)程使用”。由于我是初學(xué)者,我不知道如何解決這個(gè)問題。我知道FileAccess, FileMode,F(xiàn)ileStream但我從未使用過它們,并且認(rèn)為它們?cè)谶@一點(diǎn)上沒有幫助。這是 Main() 方法之前的構(gòu)造函數(shù)public AccountApplication() { Process process = Process.Start("notepad.exe", textFilePath); process.WaitForExit(); }以及使用此構(gòu)造函數(shù)的 Main() 方法的一部分 TextFileWriting: AccountApplication openFile; Console.Clear(); Console.ForegroundColor = ConsoleColor.Gray; Console.Write("Enter a file name: "); string filename = Console.ReadLine(); if (filename == "") { goto TextFileWriting; } textFilePath = Path.Combine(currentUserFolder, filename + ".txt"); if (File.Exists(textFilePath)) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("File You specified already has been created. Do you want to overwrite or edit it? (edit/overwrite)"); string userAnswer = Console.ReadLine(); if (userAnswer == "edit") { openFile = new AccountApplication(); goto MainMenu; } else if (userAnswer == "overwrite") { File.CreateText(textFilePath); openFile = new AccountApplication(); goto MainMenu; } else if (userAnswer == "") { goto TextFileWriting; } }記事本打開,程序正在等待它關(guān)閉。用戶無法做的一件事是保存所做的更改。
1 回答

蝴蝶刀刀
TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超8個(gè)贊
下面的行為StreamWriter
您創(chuàng)建了一個(gè):
File.CreateText(textFilePath);
它旨在像這樣使用:
using (var writer = File.CreateText(textFilePath)) { writer.WriteLine("Hi!"); };
如果您不想向文件寫入任何內(nèi)容,請(qǐng)StreamWriter
立即關(guān)閉:
File.CreateText(textFilePath).Close();
- 1 回答
- 0 關(guān)注
- 116 瀏覽
添加回答
舉報(bào)
0/150
提交
取消