如何在编辑使用Process.Start()打开的文本文件时修复“由其他进程使用”错误?

问题描述 投票:0回答:1

我在c#中创建一个控制台应用程序。我使用Process.Start()函数打开文本文件,可以直接在记事本中编辑,程序等待记事本关闭。但是在尝试保存文件时,会弹出一条警告消息,说“另一个进程正在使用该文件”。

由于我是初学者,我不知道如何解决这个问题。我知道FileAccessFileModeFileStream,但我从未使用过它们,并且认为它们不会在这一点上提供帮助。

这是Main()方法之前的构造函数

public AccountApplication()
        {
            Process process = Process.Start("notepad.exe", textFilePath);
            process.WaitForExit();
        }

并且是使用此构造函数的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;
                    }

                }
                else if (!File.Exists(textFilePath))
                {
                    File.CreateText(textFilePath);
                    openFile = new AccountApplication();
                    goto MainMenu;
                }

记事本打开,程序正在等待它关闭。用户无法做的一件事是保存所做的更改。

c# editing process.start
1个回答
1
投票

下面的行为您创建了一个StreamWriter

File.CreateText(textFilePath);

它的目的是这样使用:

using (var writer = File.CreateText(textFilePath))
{
    writer.WriteLine("Hi!");
};

如果您不想在文件中写入任何内容,请立即关闭StreamWriter

File.CreateText(textFilePath).Close();
© www.soinside.com 2019 - 2024. All rights reserved.