2016-02-15 27 views
0

到目前爲止,我已經編寫代碼來檢查文件名是否存在,並輸出一個錯誤,如果沒有文件。檢查一個文件的整數,然後輸出一個警告C#

//does the file exist? 
    if (!System.IO.File.Exists(fileName)) 
    { 
     MessageBox.Show("Error: No such file."); 
     return; 
    } 

現在我想檢查,看看是否該文件包含整數,如果有文件中沒有整數,然後我需要輸出警告說,該文件不包含整數。當涉及到這個代碼時,我不知道從哪裏開始。是否有一個特定的命令只是自動檢查整數?

到目前爲止,我已經寫了這個代碼到字符串整數轉換從一個文件(我創建了一個包含整數)

// convert each string into an integer and store in "eachInt[]" 
    string fileContents = System.IO.File.ReadAllText(fileName); 
    string[] eachString = fileContents.Split(new char[] { ' ', '\t', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); 
    int[] eachInt = new int[eachString.Length]; 
    for (int i = 0; i < eachString.Length; i++) 
     eachInt[i] = int.Parse(eachString[i]); 
+0

你能不能給我們的文件內容的樣本進行檢查? –

回答

1

您可以使用:

if(fileContents.Any(char.IsDigit)) 

既然你已經讀取字符串中的文件內容。

如果你不希望加載在內存中的所有文件,那麼你可以做

foreach (var line in File.ReadLines("filePath")) 
{ 
    if (line.Any(char.IsDigit)) 
    { 
     //number found. 
     return;//return found etc 
    } 
} 
+0

謝謝!這正是我需要幫助我走的!真的很感謝幫助! – MrTNader

相關問題