基于问题的第一句话:“我正在尝试将表示完整文件的 Byte[] 数组写入文件。”
阻力最小的路径是:
File.WriteAllBytes(string path, byte[] bytes)
记录在这里:
System.IO.File.WriteAllBytes - MSDN
您可以使用 BinaryWriter
对象。
protected bool SaveData(string FileName, byte[] Data)
{
BinaryWriter Writer = null;
string Name = @"C:\temp\yourfile.name";
try
{
// Create a new stream to write to the file
Writer = new BinaryWriter(File.OpenWrite(Name));
// Writer raw data
Writer.Write(Data);
Writer.Flush();
Writer.Close();
}
catch
{
//...
return false;
}
return true;
}
编辑: 糟糕,忘记了 finally
部分...可以说它留给读者作为练习 ;-)
有一个静态方法 System.IO.File.WriteAllBytes
您可以使用采用 Stream 的 System.IO.BinaryWriter
来执行此操作:
var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);
Close()
之前调用 Flush()
毫无意义,因为 Close()
将刷新。更好的是使用 using
子句,它也将刷新'n'close。
您可以使用 FileStream.Write(byte[] array, int offset, int count) 方法将其写出。
如果您的数组名称是“myArray”,则代码将是。
myStream.Write(myArray, 0, myArray.count);
是的,为什么不呢?
fs.Write(myByteArray, 0, myByteArray.Length);
尝试 BinaryReader:
/// <summary>
/// Convert the Binary AnyFile to Byte[] format
/// </summary>
/// <param name="image"></param>
/// <returns></returns>
public static byte[] ConvertANYFileToBytes(HttpPostedFileBase image)
{
byte[] imageBytes = null;
BinaryReader reader = new BinaryReader(image.InputStream);
imageBytes = reader.ReadBytes((int)image.ContentLength);
return imageBytes;
}
ASP.NET (c#)
// 这是托管应用程序的服务器路径。
var path = @"C:\Websites\mywebsite\profiles\";
//字节数组中的文件
var imageBytes = client.DownloadData(imagePath);
//文件扩展名
var fileExtension = System.IO.Path.GetExtension(imagePath);
//写入(保存)给定路径上的文件。附加员工 ID 作为文件名和文件扩展名。
File.WriteAllBytes(path + dataTable.Rows[0]["empid"].ToString() + fileExtension, imageBytes);
下一步:
您可能需要为 iis 用户提供对配置文件文件夹的访问权限。
右键单击配置文件文件夹转到安全选项卡单击“编辑”,完全控制“IIS_IUSRS”(如果此用户不存在,则单击添加并键入“IIS_IUSRS”并单击“检查名称”。
不定期副业成功案例分享
BinaryWriter
是一次性的,因此可能应该在using
块中使用。这也意味着您可能会放弃一些额外的调用,因为 source code 表明它在处理时会进行一些清理。