2016-07-11 251 views
0

我正在讀取文件到我的C#應用​​程序並使用gzip流解壓縮tile_data BLOB。我目前通過這種方法訪問BLOB數據:等待string.contains()條件滿足

SQLiteCommand command = new SQLiteCommand(query, DbConn); 
SQLiteDataReader reader = command.ExecuteReader(); 
bool isMet = false; 
while (reader.Read()) 
{ 
    using (var file = reader.GetStream(0)) 
    using (var unzip = new GZipStream(file, CompressionMode.Decompress)) 
    using (var fileReader = new StreamReader(unzip)) 
    { 
     var line = fileReader.ReadLine(); 
     while (!fileReader.EndOfStream) 
     { 

     } 
     Console.WriteLine("End of tile_data"); 
    } 
} 
reader.Close(); 
Console.WriteLine("Reader closed"); 
Console.ReadKey(); 
} 
catch (Exception e) 
{ 
    Console.Write(e.StackTrace); 
    Console.ReadKey(); 
} 

我期待等到fileReader檢測"tertiary"(串),然後再把打印的所有數據。我試圖使用一個bool和一個嵌套的while loop,但它作爲一個無限循環回來,因此是一個問題。

,我用(與失敗)的代碼:

if (line.Contains("tertiary")) 
{ 
    isMet = true; 
} 
while (!fileReader.EndOfStream && isMet) 
{ 
    Console.WriteLine(line); 
} 

如何我只能用我的fileReader一旦條件滿足執行操作?

+0

檢查答案。告訴我它在爲你工作或不在。 – Developer

+0

在你的while循環中,你沒有讀取/處理fileReader,因此你永遠不會到達流的末尾,你的while將會是無限的。你應該在你的時候附上一個'line = fileReader.ReadLine()'來繼續閱讀。 – BasiK

回答

1

您的fileReader.EndOfStream循環僅在您的流只有一行時纔有效。問題是,你只能從流中讀取一次 - 所以除非你已經讀完了整個事情,否則你將陷入無限循環。

相反,做這樣的事情:

string line; 

while ((line = fileReader.ReadLine()) != null) 
{ 
    if (line.Contains("...")) break; // Or whatever else you want to do 
} 
0

var line = fileReader.ReadLine();是否在while循環中?

while (!fileReader.EndOfStream) 
{ 
    var line = fileReader.ReadLine(); 
    // do some other stuff 
} 
+0

哎呀,這是之前,但我想我忘了搬回來之前發佈在這裏,正在測試幾件事情。謝謝 :) –

1

您可以使用此代碼。它在字符串中找到任何字符。它爲我工作。

string matchStr = "tertiary"; 
       if (line.Any(matchStr.Contains) 
          { 
           isMet = true; 
          } 
          while (!fileReader.EndOfStream && isMet) 
          { 
           Console.WriteLine(line); 
          } 
0

嘗試是這樣的

var yourval; 
var secval = fileReader.ReadLine() 

while ((yourval = secval) != null) 
{ 
    if (line.Contains("your string here")) 
    { 
     break; 
    } 
}