我已将所选文件附加到formData中,并使用XML请求发送到服务器端。在服务器端,我需要将接收到的文件保存为二进制格式。

我现有的代码是

var httpPostedFile = System.Web.HttpContext.Current.Request.Files["MyFiles"];

var fileSave = System.Web.HttpContext.Current.Server.MapPath("SavedFiles");

Directory.CreateDirectory(fileSave);

var fileSavePath = Path.Combine(fileSave, httpPostedFile.FileName);


到此为止,已经创建了一个文件夹。我不知道如何在创建的位置将文件保存为二进制格式。

我盲目地尝试过

FileStream fs = System.IO.File.Create(fileSavePath);
byte[] b;
using (BinaryReader br = new BinaryReader(fs))
{
   b = br.ReadBytes((int)fs.Length);
}
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(b);
}


但这会引发异常。您能在这里建议如何实现我的需求吗?

最佳答案

要保存发布的文件,假设httpPostedFile不为null,则可以简单地使用SaveAs(...)

HttpPostedFile httpPostedFile = ...

// I've changed your method to use Path.GetFileName(...) to ensure that there are no path elements in the input filename.
var fileSavePath = Path.Combine(fileSave, Path.GetFileName(httpPostedFile.FileName));
httpPostedFile.SaveAs(fileSavePath);

10-06 03:31