我一直在研究这段似乎微不足道的小代码,但我仍然无法确定问题出在哪里。我的功能很简单。打开文件,复制其内容,替换内部的字符串并将其复制回原始文件(然后在文本文件中进行简单的搜索和替换)。 我真的不知道怎么做,因为我在原始文件中添加了行,所以我只创建了一个文件副本,(file.temp)副本也备份(file.temp)然后删除原始文件(文件)并将file.temp复制到文件。 我在删除文件时遇到异常。 以下是示例代码:

private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
    {
        Boolean result = false;
        FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write);
        StreamWriter sw = new StreamWriter(fs);

        StreamReader streamreader = file.OpenText();
        String originalPath = file.FullName;
        string input = streamreader.ReadToEnd();
        Console.WriteLine("input : {0}", input);

        String tempString = input.Replace(extractedMethod, modifiedMethod);
        Console.WriteLine("replaced String {0}", tempString);

        try
        {
            sw.Write(tempString);
            sw.Flush();
            sw.Close();
            sw.Dispose();
            fs.Close();
            fs.Dispose();
            streamreader.Close();
            streamreader.Dispose();

            File.Copy(originalPath, originalPath + ".old", true);
            FileInfo newFile = new FileInfo(originalPath + ".tmp");
            File.Delete(originalPath);
            File.Copy(fs., originalPath, true);

            result = true;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

        return result;
    }`

相关的例外

System.IO.IOException: The process cannot access the file 'E:\mypath\myFile.cs' because it is being used by another process.
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.Delete(String path)
   at callingMethod.modifyFile(FileInfo file, String extractedMethod, String modifiedMethod)

通常这些错误来自未关闭的文件流,但我已经处理过了。我想我已经忘记了一个重要的步骤,但无法弄清楚在哪里。 非常感谢你的帮助,

有帮助吗?

解决方案

听起来像是一个外部进程(AV?)锁定它,但是你不能首先避免这个问题吗?

private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
{
    try
    {
        string contents = File.ReadAllText(file.FullName);
        Console.WriteLine("input : {0}", contents);
        contents = contents.Replace(extractedMethod, modifiedMethod);
        Console.WriteLine("replaced String {0}", contents);
        File.WriteAllText(file.FullName, contents);
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        return false;
    }
}

其他提示

我意识到我有点迟了,但迟到总比没有好。我最近遇到了类似的问题。我使用 XMLWriter 随后更新XML文件并收到相同的错误。我找到了干净的解决方案:

XMLWriter 使用底层 FileStream 来访问修改后的文件。问题是当你调用 XMLWriter.Close()方法时,底层流不会被关闭并锁定文件。您需要做的是使用设置实例化 XMLWriter ,并指定您需要关闭该底层流。

示例:

XMLWriterSettings settings = new Settings();
settings.CloseOutput = true;
XMLWriter writer = new XMLWriter(filepath, settings);

希望它有所帮助。

我能说出最好的代码。我会启动 Sysinternals流程资源管理器并找出持有的内容文件打开。它很可能是Visual Studio。

它对我有用。

这是我的测试代码。测试运行如下:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            FileInfo f = new FileInfo(args[0]);
            bool result = modifyFile(f, args[1],args[2]);
        }
        private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod) 
        { 
            Boolean result = false; 
            FileStream fs = new FileStream(file.FullName + ".tmp", FileMode.Create, FileAccess.Write); 
            StreamWriter sw = new StreamWriter(fs); 
            StreamReader streamreader = file.OpenText(); 
            String originalPath = file.FullName; 
            string input = streamreader.ReadToEnd(); 
            Console.WriteLine("input : {0}", input); 
            String tempString = input.Replace(extractedMethod, modifiedMethod); 
            Console.WriteLine("replaced String {0}", tempString); 
            try 
            { 
                sw.Write(tempString); 
                sw.Flush(); 
                sw.Close(); 
                sw.Dispose(); 
                fs.Close(); 
                fs.Dispose(); 
                streamreader.Close(); 
                streamreader.Dispose(); 
                File.Copy(originalPath, originalPath + ".old", true); 
                FileInfo newFile = new FileInfo(originalPath + ".tmp"); 
                File.Delete(originalPath); 
                File.Copy(originalPath + ".tmp", originalPath, true); 
                result = true; 
            } 
            catch (Exception ex) 
            { 
                Console.WriteLine(ex); 
            } 
            return result; 
        }
    }
}


C:\testarea>ConsoleApplication1.exe file.txt padding testing
input :         <style type="text/css">
        <!--
         #mytable {
          border-collapse: collapse;
          width: 300px;
         }
         #mytable th,
         #mytable td
         {
          border: 1px solid #000;
          padding: 3px;
         }
         #mytable tr.highlight {
          background-color: #eee;
         }
        //-->
        </style>
replaced String         <style type="text/css">
        <!--
         #mytable {
          border-collapse: collapse;
          width: 300px;
         }
         #mytable th,
         #mytable td
         {
          border: 1px solid #000;
          testing: 3px;
         }
         #mytable tr.highlight {
          background-color: #eee;
         }
        //-->
        </style>

遇到这个错误并且没有在Web上找到任何让我正确的东西,我想我会添加另一个获得此异常的原因 - 即File Copy命令中的源路径和目标路径是相同的。我花了一段时间才弄明白,但如果源和目标路径指向同一个文件,那么在某处添加代码可能有助于抛出异常。

祝你好运!

您是否正在运行实时防病毒扫描程序? 如果是这样,您可以尝试(暂时)禁用它以查看是否正在访问您要删除的文件。 (Chris建议使用Sysinternals进程探索器是一个很好的建议)。

试试这个:它在任何情况下都有效,如果文件不存在,它会创建它然后写入它。如果已经存在,那么它就会打开并写入它没问题:

 using (FileStream fs= new FileStream(@"File.txt",FileMode.Create,FileAccess.ReadWrite))
 { 
   fs.close();
 }
 using (StreamWriter sw = new StreamWriter(@"File.txt")) 
 { 
   sw.WriteLine("bla bla bla"); 
   sw.Close(); 
 } 

创建文件后,您必须强制流释放资源:

//FSm is stream for creating file on a path//
System.IO.FileStream FS = new System.IO.FileStream(path + fname,
                                                   System.IO.FileMode.Create);
pro.CopyTo(FS);
FS.Dispose();
 System.Drawing.Image FileUploadPhoto = System.Drawing.Image.FromFile(location1);
                                 FileUploadPhoto.Save(location2);
                                 FileUploadPhoto.Dispose();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top