문제

나는 사소한 것처럼 보이는이 작은 코드를 연구 해 왔지만 여전히 문제가 어디에 있는지 알 수 없습니다. 내 기능은 매우 간단한 일을합니다. 파일을 열고 내용을 복사하고 문자열을 바꾸고 원본 파일로 다시 복사합니다 (간단한 검색 및 텍스트 파일 내부를 교체). 원본 파일에 줄을 추가 할 때 그렇게하는 방법을 실제로 몰랐으므로 파일의 사본 만 만들었습니다 (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 프로세스 탐색기 파일을 열어 놓은 내용을 알아보십시오. 비주얼 스튜디오 일 수 있습니다.

그것은 나를 위해 일했다.

다음은 내 테스트 코드입니다. 테스트 실행은 다음과 같습니다.

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>

이 오류를 발견하고 웹에서 제대로 설정 한 것을 찾지 못한 후에는이 예외를 얻는 또 다른 이유, 즉 파일 복사 명령의 소스 및 대상 경로가 동일하다는 것을 추가 할 것이라고 생각했습니다. 그것을 알아내는 데 시간이 걸렸지 만 소스와 대상 경로가 동일한 파일을 가리키는 경우 예외를 던지기 위해 코드를 추가하는 데 도움이 될 수 있습니다.

행운을 빕니다!

우연히 실시간 바이러스 백신 스캐너를 실행하고 있습니까? 그렇다면 삭제하려는 파일에 액세스하는 것인지 확인하기 위해 (임시) 비활성화하려고 시도 할 수 있습니다. (Sysinnals Process Explorer를 사용하려는 Chris의 제안은 좋은 것입니다).

이것을 시도하십시오 : 어쨌든 파일이 존재하지 않으면 파일이 생성 된 다음 작성한 다음 작성합니다. 그리고 이미 존재한다면 문제가 없으면 열어서 쓸 것입니다.

 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