2016-10-05 9 views
0

간단한 텍스트 편집기를 만들고 저장하는 데 문제가 있습니다. 그래서 절약을위한 2 개 코드가, 하나는 버튼 모든 것이 완벽하게 작동로 저장하는 경우, 파일 사용하여 버튼 및 다른 Ctrl + S를 키보드 바로 가기를 저장하는 것입니다,하지만 난 바로 가기로 저장할 때이 오류가 얻을 : 여기C# streamwriter "프로세스가 파일을 액세스 할 수 없습니다."오류가 발생하여 닫히고 처리되었습니다.

"process cannot access file because it's used by another process"

 saveFileDialog1.FileName = currentname; 

     if (saveFileDialog1.ShowDialog() == DialogResult.OK) 
     { 

      StreamWriter writer = new StreamWriter(saveFileDialog1.OpenFile()); 

      writer.WriteLine(richTextBox1.Text); 

      writer.Dispose(); 
      writer.Close(); 

      //so i have tabs in my editor so user can switch between them. 
      //and this is the only way i found which tab is opened now. 
      for (int i = 0; i < labels.Count; i++) 
      { 
       //i created new class that holds some variables including "isUsed" 
       //and Label itself. 
       if (labels[i].isUsed) 
       { 
        labels[i].Text = Path.GetFileName(saveFileDialog1.FileName); 
        labels[i].setText(labels[i].Text); 
        labels[i].path = saveFileDialog1.FileName; 
        break; 
       } 
      } 

     }` 

스크립트가 위의 정상 작동 ',하지만 다음과 같은 스크립트를하지 않습니다 : 버튼 내 코드가 저장되고 여기에

 public void save(){ 

     bool found = false; 
     //that is class i made. 
     AdvancedLabel label = new AdvancedLabel(); 

     //I hold all tabs in "Labels" List. 
     for (int i = 0; i < labels.Count; i++) 
     { 
      //so if loop found the tab that is opened now... 
      if (labels[i].isUsed) 
      { 
       label = labels[i]; 
       found = true; 
       break; 
      } 
     } 
     if (found) 
     { 
      try 
      { 

       label.label.Text.Remove(label.label.Text.Length - 1); 

       //here i always get this error. 
       StreamWriter writer = new StreamWriter(label.path); 

       writer.WriteLine(richTextBox1.Text); 
       label.setText(label.Text.Remove(label.Text.Length - 1)); 
       writer.Dispose(); 
       writer.Close(); 

      } 
      catch (Exception e) 
      { 
       status.Text = "status: " + e.Message + ". Failed to save :("; 

      } 
     } 
    } 

전체 오류입니다 :

An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll

Additional information: The process cannot access the file 'C:\Users\nika\Desktop\dd.html' because it is being used by another process. 

편집 : 당신

덕분에 모든 사람, 내가 여기 내가 생각 해낸 원하든되는 문 "을 사용하여"사용되어야 이해되는 :

enter image description here

나는 그 것을 언급하는 것을 잊었습니다 또한 stramreader을 사용하여 파일을 여는 중입니다. "사용"문으로 변경했지만 같은 일이 일어났습니다. 지금도 사용하고 있습니다. File.appendalltext 문. 이것은 또한 작동하지만 버튼으로 저장하는 경우에만 작동합니다. 내가 그것을 (파일 오프너되지 작가) 변경 방법은 다음과

은`

  using (var sr = new StreamReader(openFileDialog1.FileName)) 
      { 
       bool found = false; 

       for (int i = 0; i < labels.Count; i++) 
       { 
        if (labels[i].path == openFileDialog1.FileName) 
        { 
         found = true; 

         break; 
        } 
       } 
       if (!found) 
       { 

        richTextBox1.Text = ""; 
        richTextBox1.Text = sr.ReadToEnd(); 

        spawnLabel(); 
       } 
      }` 

PS (이 그렇게 바보 같은 소리)

@GauravKP가 제안 :

enter image description here

어떤 도움을 주시면 감사하겠습니다! 감사!

- 닉

+1

을 따라서 오류가 무엇 때문에 당신 실제로?형식 'System.IO.IOException'의 – Jim

+0

@Jim 처리되지 않은 예외가 mscorlib.dll에서 추가 정보를 발생 프로세스가 파일 'C를 : \ 사용자 \ 니카 바탕 화면 \ dd.html \'에 액세스 할 수 없습니다 그것은 사용하고 있기 때문에 다른 프로세스에 의해. – Nick

+0

왜 downvote? 적어도 내가 설명하기 때문에이 실수를 미래에하지는 마라. !!! – Nick

답변

0

스트림 개체를 처리 할 때는 항상 "사용"을 사용하십시오. 원칙적으로

, 당신은으로 IDisposable 개체를 사용할 때, 당신은 선언하고 문을 사용하여 에 인스턴스화해야합니다

using (var stream = ...) 
{ 
    /* code */ 

    stream.Close(); 
} 

는이 문서의 말씀입니다. using 문은 올바른 방법으로 개체의 Dispose 메서드를 호출합니다..

올바른 방법은 여기에 핵심 단어입니다.

우리는 "개체의 소비자가 폐기 메소드를 호출하지 못하기 때문에 관리되지 않는 리소스를 해제하지 않을 위험이 항상 존재 ."폐기를 호출하더라도

+0

내가이 권리를 얻었습니까? '사용 (VAR 작가 = 새에서는 StreamWriter (label.path)) { writer.WriteLine (richTextBox1.Text); label.setText (label.Text.Remove (label.Text.Length - 1)); writer.Close(); }' – Nick

+0

예. 다시 "writer.close()"를 호출 할 필요가 없습니다. 사용하면 그것을 돌볼 것입니다. – Naidu

+1

당신은 코드가 더 그냥 할 ['File.AppendAllText (label.path, richTextBox1.Text),'] 간단하게 할 수 @Nick (https://msdn.microsoft.com/en-us/library/ms143356 (절 = vs.110) .aspx) 및 StreamWriter 완전히 제거하십시오. –