2014-06-10 31 views
1

在這部分如何結束這個過程?

if (File.Exists(filePath)) { 
     string status = new StreamReader(File.OpenRead(filePath)).ReadLine(); 

     if (status != "SUCCEEDED") { 
      File.Delete(filePath); 
      createDb(); 
     } 
} 

程序給出與消息

過程異常不能訪問該文件「\ status.txt中」,因爲它正在被另一個過程中使用 。

如何解決這個問題?

+7

您需要關閉流。 – SLaks

+0

謝謝,它做的工作 – user3547145

回答

4

修改代碼以這樣的事:

if (File.Exists(filePath)) 
{ 
    string status; 
    using(var streamReader = new StreamReader(filePath)) 
    { 
     status = streamReader.ReadLine(); 
    } 

    if (status != "SUCCEEDED") 
    { 
     File.Delete(filePath); 
     createDb(); 
    } 
} 
0

你需要刪除它之前關閉該文件或使用塊寫。

if (File.Exists(filePath)) 
{ 
    string status= string.Empty; 
    using (var stream = new StreamReader(File.OpenRead(filePath))) 
    { 
     status = stream.ReadLine(); 
    } 
    if (status != "SUCCEEDED") 
    { 
     File.Delete(filePath); 
     createDb(); 
    } 
} 
+2

'status'是一個字符串。你不能關閉一個字符串。 –

+0

@thefiloe:我的不好。我在回答時非常匆忙。更正了答案。謝謝。 – Ricky

1

使用using模式:

if (File.Exists(filePath)) { 
    using(var stream = new StreamReader(File.OpenRead(filePath))) 
    { 
     var status = stream.ReadLine(); 
     if (status != "SUCCEEDED") 
     { 
     File.Delete(filePath); 
     createDb(); 
     } 
    } 
} 

那麼如果somene其他人使用該文件,可以打開下面的流:

new FileStream(fi.FullName, FileMode.Open, FileAccess.Read, FileShare.Delete | FileShare.ReadWrite)) 

螞蟻,然後傳遞給StreamReader的構造函數。

+0

你其實不需要使用'File.OpenRead'。你可以使用這個ctor:http://msdn.microsoft.com/de-de/library/vstudio/f2ke0fzy –

+0

@thefiloe正確,只是重用OP代碼,但對於其他答案仍然有用。 –

1

你應該關閉流刪除該文件之前 試試這個

if (File.Exists(filePath)) 
     { 
      string status= string.Empty; 
      using (var stream = new StreamReader(File.OpenRead(filePath))) 
      { 
       status = stream.ReadLine(); 
      } 
      if (status != "SUCCEEDED") 
      { 
       File.Delete(filePath); 
       createDb(); 
      } 
     }