2011-12-28 2 views
1

이 코드를 가지고 있습니다. 아이디어는 파일을 읽고 파일을 삭제하는 것입니다. 파일을 삭제할 수 없습니다. "프로세스가 파일에 액세스 할 수 없습니다."

   StreamReader sr = new StreamReader(path); 

       s = sr.ReadLine(); 
       if ((s != null)) 
       { 
       sr.ReadLine(); 
        do 
        { 
        // I start to read and get the characters 

        }while (!(sr.EndOfStream)); 
       } 
       sr.close(); 

하고 가까이에서는 StreamReader 후

, 나는 파일을 삭제하려고하지만 난 할 수 없습니다 :

는 "프로세스가 파일을 액세스 할 수 없습니다 다른 프로세스에서 사용하고 있기 때문에"

어떻게해야합니까? 다음과 같이 using 성명에서 코드를 둘러싸 후

+0

엑셀 파일 또는 다른 파일입니까? – Dotnet

+2

코드 (조각)는 지나치게 복잡해 보이며 당신이 묘사 한 것으로부터 약해 보이는 것이 목표입니다. 적어도 파일을 삭제하려고하는 부분까지 전체 코드/기능을 표시하십시오. –

+0

그것은 txt 코드이며 sr.Dispose()로 시도하고 작동하지 않습니다 – jobormo

답변

2

시도의 삭제 :

using( StreamReader sr = new StreamReader(path)) 
{ 
    ... 
} 

그 중 하나가 작동하지 않는 경우는, 다음 다른 프로세스가 파일을 잠근.

using (var reader = new StreamReader(path)) 
{ 
    string line; 
    while ((line = reader.ReadLine()) != null) 
    { 
     // do something with the line that was just read from the file 
    } 
} 

// At this stage you can safely delete the file 
File.Delete(path); 

또는 파일이 작은 경우에도 모든를로드 할 수

+0

나는 다른 프로세스가 내 파일을 잠글 게했다 : S, 모든 사람들에게 thx !! – jobormo

+0

아, 또 다른 행복한 고객. 도와 줘서 기뻐. –

0

왜 파일을 줄이 다음과 같은 시도 읽으려면이

using (StreamReader sr= new StreamReader(your Path here)) 
{ 
    // do your stuff 
} 
0

같은 어떤 것을 사용하지 않는 메모리에있는 행 :

string[] lines = File.ReadAllLines(path); 
// Do something with the lines that were read 
... 
// At this stage you can safely delete the file 
File.Delete(path); 
관련 문제