天天看点

C#读取TXT文件

public string GetTxt(string fileName)
    {
        string line = string.Empty;
        StringBuilder sb = new StringBuilder();

        try
        {
            using (StreamReader sr = new StreamReader(fileName, Encoding.Default))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    string[] stringArray = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < stringArray.Length; i++)
                    {
                        if (stringArray[0].Length != 16)
                        {
                            continue;
                        }
                        sb.AppendLine(i + "的值是:" + stringArray[i] + "<br />");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Response.Write("文件读取错误");
            Response.Write(ex.Message);
        }
        return sb.ToString();
    }