覆盖当前打开的文件并在 C# 中使用

Overwrite an file which is currently open and it use in c#

我正在使用 C# 创建一个具有日志记录功能的 GUI。当我创建日志文件时,我为它提供了一个文件名。但我有以下问题。例如,如果文件已经在我的桌面后台打开,并且我想将我的文件名命名为相同的文件名,我会收到如下异常消息:

The process cannot access the file 'C:\blah\blah\mytest.csv' because it is being used by another process.

我正在使用以下代码来检查文件是否存在,并使用 streamwriter 创建新文件。

if (FileUtils.Exists(fileName))
            {
                if (!FileUtils.Delete(fileName))
                {
                    cout<< Error replacing log file, it might be used by another process"; 
                }             
            }

//Exception handling
     public static bool Delete(string myfiletowrite)
            {
                try
                {
                    File.Delete(myfiletowrite);
                    return true;
                }
                catch (IOException)
                {
                    return false;
                }
            } 
myfile= new StreamWriter(myfiletowrite, true); //exception occurs here when I try to write to myfiletowrite which is currently open 

我不确定如何关闭这个在后台打开的文件,以便我可以写入这个文件。如果有人可以帮助我,我将不胜感激。

如果其他应用程序没有明确允许(通过共享模式),则无法打开文件进行写入。

如果另一个应用程序在您的控制之下,您有一些选择(使用 [=10= 打开文件],在两个应用程序之间实施一些通信协议,使用通用服务访问文件,... ).

最好的选择是选择一个不同的文件名。