C# 读取大文件

/// <summary>
/// 读取大文件,每次读取1M,优化可考虑分割读取
/// </summary>
/// <returns></returns>
public static string ReadBinaryFileToString(FileStream fs)
{
    if (fs != null)
    {
        string returnStr = ""; //保存结果字符串
        try
        {
            byte[] byteArray = new byte[1024 * 1024];//开辟1M内存空间

            BinaryReader reader = new BinaryReader(fs);

            while (reader.Read(byteArray, 0, byteArray.Length) > 0)
            {
                string content = AppTool.DEFAULT_FILE_ENCODING.GetString(byteArray);
                returnStr += content;
            }

            return returnStr;
        }
        catch (Exception e)
        {
            Debug.WriteLine(string.Format("读取文件出错:消息={0},堆栈={1}", e.Message, e.StackTrace));
        }          
    }
    return null;
}

猜你喜欢

转载自blog.csdn.net/qq_35106907/article/details/85337376