C# 将文件转化成byte[]数组

C# 将文件转化成byte[]数组

原文链接 https://www.cnblogs.com/wangfuyou/p/5063703.html

1.

/// <summary>

/// 将文件转换成byte[] 数组

/// </summary>

/// <param name="fileUrl">文件路径文件名称</param>

/// <returns>byte[]</returns>

protected byte[] GetFileData(string fileUrl)

{

  FileStream fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);

  try

  {

    byte[] buffur = new byte[fs.Length];

    fs.Read(buffur, 0, (int)fs.Length);

    return buffur;

  }

  catch (Exception ex)

  {

    //MessageBoxHelper.ShowPrompt(ex.Message);

    return null;

  }

  finally

  {

    if (fs != null)

    {

      //关闭资源

      fs.Close();

    }

  }

}

2.

/// <summary>

/// 将文件转换成byte[] 数组

/// </summary>

/// <param name="fileUrl">文件路径文件名称</param>

/// <returns>byte[]</returns>

protected byte[] AuthGetFileData(string fileUrl)

{

  using (FileStream fs = new FileStream(fileUrl, FileMode.OpenOrCreate, FileAccess.ReadWrite))

  {

    byte[] buffur = new byte[fs.Length];

    using (BinaryWriter bw = new BinaryWriter(fs))

    {

      bw.Write(buffur);

      bw.Close();

    }

    return buffur;

  }

}

1.

/// <summary>

/// 将文件转换成byte[] 数组

/// </summary>

/// <param name="fileUrl">文件路径文件名称</param>

/// <returns>byte[]</returns>

protected byte[] GetFileData(string fileUrl)

{

  FileStream fs = new FileStream(fileUrl, FileMode.Open, FileAccess.Read);

  try

  {

    byte[] buffur = new byte[fs.Length];

    fs.Read(buffur, 0, (int)fs.Length);

    return buffur;

  }

  catch (Exception ex)

  {

    //MessageBoxHelper.ShowPrompt(ex.Message);

    return null;

  }

  finally

  {

    if (fs != null)

    {

      //关闭资源

      fs.Close();

    }

  }

}

2.

/// <summary>

/// 将文件转换成byte[] 数组

/// </summary>

/// <param name="fileUrl">文件路径文件名称</param>

/// <returns>byte[]</returns>

protected byte[] AuthGetFileData(string fileUrl)

{

  using (FileStream fs = new FileStream(fileUrl, FileMode.OpenOrCreate, FileAccess.ReadWrite))

  {

    byte[] buffur = new byte[fs.Length];

    using (BinaryWriter bw = new BinaryWriter(fs))

    {

      bw.Write(buffur);

      bw.Close();

    }

    return buffur;

  }

}