检查文件中的整数,然后输出警告 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]);

您可以使用:

if(fileContents.Any(char.IsDigit))

由于您已经读取了字符串中的文件内容。

如果您不想将所有文件加载到内存中,那么您可以这样做

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

最新更新