2013-07-24 8 views
0

텍스트 파일이 없으면 텍스트 파일을 작성하고 텍스트를 추가하는 직후입니다. 그러나 제 컴파일러는 다른 프로세스에서 사용하고 있다고 말합니다.이 프로세스는 방금 생성 된 것으로 가정합니다. 이 문제를 어떻게 해결할 수 있습니까?작성한 후 텍스트 파일 편집

코드

//If the text document doesn't exist, create it 
if (!File.Exists(set.cuLocation)) 
{ 
    File.CreateText(set.cuLocation); 
} 

//If the text file after being moved is empty, edit it to say the previous folder's name 
System.IO.StreamReader objReader = new System.IO.StreamReader(set.cuLocation); 
set.currentUser = objReader.ReadLine(); 
objReader.Close(); 
if (set.currentUser == null) 
{ 
    File.WriteAllText(set.cuLocation, set.each2); 
} 

답변

5

CreateText 방법은 실제로 StreamWriter 객체를 생성 (반환) excerpt-. 당신은 결코 그 흐름을 닫지 않을 것입니다. 성취하려는 것은 무엇입니까? 왜 빈 파일을 읽으려고합니까? 작성중인 글의 참조 번호 인 StreamWriter을 작성하여 글쓰기에 사용하십시오.

StreamWriter sw = File.CreateText(set.cuLocation); 

다음 sw.Write

는 참조 용으로 http://msdn.microsoft.com/en-us/library/system.io.streamwriter.write.aspx를 참조 호출합니다.

끝나면 sw.Close으로 전화하십시오.

작성하는 동안 예외가 발생 될 수 있습니다. 이렇게하면 스트림이 닫히는 것을 방지 할 수 있습니다.

이 문제를 해결하는 좋은 패턴은 StreamWriterusing 블록으로 묶는 것입니다. 자세한 내용은이 질문을 참조 : Is it necessary to wrap StreamWriter in a using block?

+0

해당 스트림을 닫으려면 어떻게해야합니까? – TheUnrealMegashark

+1

@TheUnrealMegashark 설명서를 읽는 것이 좋습니다. 여기에있는 예제는 어떻게하는지 보여줍니다. –

+0

@ TheUnrealMegashark, 그냥 끝에 .Close()를 추가하십시오. – gunr2171

1

닫기 메소드를 호출 잊지 마세요 :

당신은 자동으로 스트림을 종료하는 using 블록에 묶어야 할 수
if (!File.Exists(set.cuLocation)) 
{ 
    File.Create(set.cuLocation) 
     .Close(); 
} 
0

:

if (!File.Exists(set.cuLocation)) 
{ 
    File.CreateText(set.cuLocation); 
} 

using(System.IO.StreamReader objReader = new System.IO.StreamReader(set.cuLocation)) 
{ 
    set.currentUser = objReader.ReadLine(); 
} 

if (set.currentUser == null) 
{ 
    File.WriteAllText(set.cuLocation, set.each2); 
} 
관련 문제