繁体   English   中英

编辑使用Process.Start()打开的文本文件时,如何解决“由另一个进程使用”的错误?

[英]How to fix “used by another process” error when editing a text file which was opened using Process.Start()?

我在用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;
                }

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

下面的行为您创建一个StreamWriter

File.CreateText(textFilePath);

它旨在像这样使用:

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

如果您不想向文件写入任何内容,只需立即关闭StreamWriter

File.CreateText(textFilePath).Close();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM