首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >System.IO.IOException:另一个进程使用的文件

System.IO.IOException:另一个进程使用的文件
EN

Stack Overflow用户
提问于 2009-06-22 03:51:41
回答 10查看 150.8K关注 0票数 26

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

代码语言:javascript
复制
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;
    }`

和相关的异常

代码语言:javascript
复制
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)

通常这些错误来自未关闭的文件流,但我已经注意到这一点。我想我忘记了一个重要的步骤,但我想不出在哪里。非常感谢你的帮助,

EN

Stack Overflow用户

发布于 2009-06-22 04:23:46

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

票数 3
EN
查看全部 10 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1025407

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档