2016-08-16 1 views
1

이 문제에 유의해야합니다.파일 저장 오류

void testSave() 
    { 
     fileName = curMonth.Text + curYear.Text + ".csv"; 
     if (!File.Exists(path+fileName)) 
     { 
      File.Create(path + fileName); 
     } 
     else if (File.Exists(path + fileName)) 
     { 
     try 
      { 
       lines = curDate.Text + "," + myDesc.Text + "," + myAmount.Text; 
       File.AppendAllText(path + fileName, lines + Environment.NewLine); 
       TextWriter tw = new StreamWriter(path + fileName, true); 
       tw.Close(); 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     }    
    } 

오류는 아래와 같이 나올 :

프로세스가 파일 'C를 : \ 사용자를 ... \ File.csv'를 액세스 할 수 없습니다 다른 프로세스에서 사용하고 있기 때문이다.

내가 추천 할 수있는 제안이나 해결책이 있으십니까? 감사합니다.

+0

당신은 File.AppendAllText''을 제외한 코드의 모든 라인을 제거 할 수 있습니다. 파일 존재 여부를 확인하고 수동으로 파일을 만들 필요가 없습니다. 'File.AppendAllText'는 존재하지 않는 파일을 생성합니다. 'TextWriter'를 사용하여 아무 일도하지 않습니다. 단순히 파일을 열고 파일에 쓰지 않고 닫습니다. –

+0

파일이 존재하는지 확인하고 싶습니다. 새 파일 인 경우 데이터가 들어가기 전에 헤더를 추가하고 싶습니다. 그렇게 할 방법이 있다면? – NewBieS

답변

0
  • File.Create(path + fileName); 다시 열 수 없으므로.

  • 원하는 경우 else 키워드를 제거하십시오.

    void testSave() 
    { 
        fileName = curMonth.Text + curYear.Text + ".csv"; 
        if (!File.Exists(path+fileName)) 
        { 
         try 
         { 
          File.Create(path + fileName).Close(); 
         } 
         catch (Exception ex) 
         { 
          MessageBox.Show(ex.Message); 
         } 
        } 
    
        try 
        { 
         lines = curDate.Text + "," + myDesc.Text + "," + myAmount.Text; 
         File.AppendAllText(path + fileName, lines + Environment.NewLine); 
         TextWriter tw = new StreamWriter(path + fileName, true); 
         tw.Close(); 
        } 
        catch (Exception ex) 
        { 
         MessageBox.Show(ex.Message); 
        } 
    } 
    
+0

여전히 같은 문제가 발생합니다 ... – NewBieS

+0

모든 폴더가 만들어 졌습니까? –

+0

예, 파일이 생성되지만 데이터를 가져올 수 없습니다. – NewBieS