天天看點

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();
    }