繁体   English   中英

覆盖当前打开并在 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.

我正在使用以下代码来检查文件是否存在并使用流编写器创建新文件。

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 

我不确定如何关闭这个在后台打开的文件,以便我可以写入这个文件。 我很感激有人可以帮助我解决这个问题。

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

如果另一个应用程序在你的控制之下,你有一些选择(用FileShare.Write打开文件,在两个应用程序之间实现一些通信协议,使用公共服务来访问文件,......)。

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

暂无
暂无

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

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