development

File.Create ()를 사용한 후 다른 프로세스에서 사용중인 파일

big-blog 2020. 8. 5. 07:26
반응형

File.Create ()를 사용한 후 다른 프로세스에서 사용중인 파일


런타임에 파일이 존재하는지 감지하려고합니다.없는 경우 파일을 만듭니다. 그러나 쓰려고 할 때이 오류가 발생합니다.

프로세스가 다른 프로세스에서 사용 중이므로 'myfile.ext'파일에 액세스 할 수 없습니다.

string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
if (!File.Exists(filePath)) 
{ 
    File.Create(filePath); 
} 

using (StreamWriter sw = File.AppendText(filePath)) 
{ 
    //write my text 
}

그것을 고치는 방법에 대한 아이디어가 있습니까?


File.Create메소드는 파일을 작성하고 파일을 엽니 다 FileStream. 따라서 파일이 이미 열려 있습니다. 실제로 파일이 필요하지 않습니다.

string filePath = @"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
    //write to the file
}

StreamWriter생성자 의 부울로 인해 파일이있는 경우 내용이 추가됩니다.


    File.Create(FilePath).Close();
    File.WriteAllText(FileText);

이 답변을 업데이트하여 이것이 실제로 모든 텍스트를 작성하는 가장 효율적인 방법은 아니라고 말하고 싶습니다. 빠르고 더러운 것이 필요한 경우에만이 코드를 사용해야합니다.

나는이 질문에 대답했을 때 어린 프로그래머였습니다. 그리고 그때 나는이 대답을 생각해 낸 일종의 천재라고 생각했습니다.


텍스트 파일을 만들 때 다음 코드를 사용할 수 있습니다.

System.IO.File.WriteAllText("c:\test.txt", "all of your content here");

귀하의 의견의 코드를 사용합니다. 생성 한 파일 (스트림)을 닫아야합니다. File.Create는 파일 스트림을 방금 생성 된 파일로 반환합니다.

string filePath = "filepath here";
if (!System.IO.File.Exists(filePath))
{
    System.IO.FileStream f = System.IO.File.Create(filePath);
    f.Close();
}
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
{ 
    //write my text 
}

FileStream fs= File.Create(ConfigurationManager.AppSettings["file"]);
fs.Close();

File.Create는 FileStream을 반환합니다. 파일에 쓸 때이를 닫아야합니다.

using (FileStream fs = File.Create(path, 1024)) 
        {
            Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
            // Add some information to the file.
            fs.Write(info, 0, info.Length);
        }

파일을 자동으로 닫는 데 사용할 수 있습니다.


코드 스 니펫으로 질문을 업데이트했습니다. 들여 쓰기가 제대로 된 후에는 문제가 무엇인지 즉시 알 수 있습니다. 사용하는 File.Create()것이지만 FileStream반환 하는 것을 닫지 마십시오 .

그런 식으로 이렇게하면, 불필요 StreamWriter이미 기존 파일에 추가 허용 하고 아직 존재하지 않는 경우 새 파일을 생성. 이처럼 :

  string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre); 
  using (StreamWriter sw = new StreamWriter(filePath, true)) {
    //write my text 
  }

StreamWriter생성자를 사용 합니다 .


이 질문은 이미 답변되었지만 여기에 디렉토리가 있는지 확인하고 텍스트 파일이 있으면 끝에 숫자를 추가하는 실제 솔루션이 있습니다. 필자가 작성한 Windows 서비스에서 매일 로그 파일을 만드는 데 이것을 사용합니다. 나는 이것이 누군가를 돕기를 바랍니다.

// How to create a log file with a sortable date and add numbering to it if it already exists.
public void CreateLogFile()
{
    // filePath usually comes from the App.config file. I've written the value explicitly here for demo purposes.
    var filePath = "C:\\Logs";

    // Append a backslash if one is not present at the end of the file path.
    if (!filePath.EndsWith("\\"))
    {
        filePath += "\\";
    }

    // Create the path if it doesn't exist.
    if (!Directory.Exists(filePath))
    {
        Directory.CreateDirectory(filePath);
    }

    // Create the file name with a calendar sortable date on the end.
    var now = DateTime.Now;
    filePath += string.Format("Daily Log [{0}-{1}-{2}].txt", now.Year, now.Month, now.Day);

    // Check if the file that is about to be created already exists. If so, append a number to the end.
    if (File.Exists(filePath))
    {
        var counter = 1;
        filePath = filePath.Replace(".txt", " (" + counter + ").txt");
        while (File.Exists(filePath))
        {
            filePath = filePath.Replace("(" + counter + ").txt", "(" + (counter + 1) + ").txt");
            counter++;
        }
    }

    // Note that after the file is created, the file stream is still open. It needs to be closed
    // once it is created if other methods need to access it.
    using (var file = File.Create(filePath))
    {
        file.Close();
    }
}

나는 이것이 오래된 질문이라는 것을 알고 있지만, 당신이 여전히 사용할 수 있도록 File.Create("filename")"추가 하고 싶습니다 .Dispose().

File.Create("filename").Dispose();

이런 식으로 다음 프로세스에서 사용할 파일을 만들고 닫습니다.


나는이 예외의 이유를 알고 있다고 생각합니다. 이 코드 스 니펫을 여러 스레드에서 실행하고있을 수 있습니다.


Try this: It works in any case, if the file doesn't exists, it will create it and then write to it. And if already exists, no problem it will open and write to it :

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(); 
 } 

참고URL : https://stackoverflow.com/questions/2781357/file-being-used-by-another-process-after-using-file-create

반응형