可以将字节[]数组写入C#文件中吗?

问题描述:

我试图写出一个Byte[]数组表示一个完整的文件到一个文件。可以将字节[]数组写入C#文件中吗?

来自客户端的原始文件通过TCP发送,然后由服务器接收。接收到的流被读取到一个字节数组,然后发送给这个类来处理。

这主要是为了确保接收TCPClient已准备好下一个流,并将接收端与处理端分开。

FileStream类不会将字节数组作为参数或另一个Stream对象(它允许您将字节写入它)。

我的目标是从原来的一个不同的线程(与TCPClient一个)完成处理。

我不知道如何实现这一点,我应该尝试什么?

基于问题的第一句话:“我想写出一个byte []数组代表一个完整的文件到一个文件中。”

阻力最小的路径将是:

File.WriteAllBytes(string path, byte[] bytes) 

这里记载:

System.IO.File.WriteAllBytes - MSDN

是的,为什么不呢?

fs.Write(myByteArray, 0, myByteArray.Length); 

可以使用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部分......可以说,这是留给作为练习读者;-)

+0

可以说,我已经收到压缩数据,我已经解压缩它的byte []。使用上面的函数可以创建文件吗?任何教程或演示在线? – Cannon 2011-06-15 03:52:22

+0

@buffer_overflow:如果你想恢复原始文件,你需要先压缩它。看看可能的实现装饰模式:http://en.wikipedia.org/wiki/Decorator_pattern – Treb 2011-06-15 10:52:22

+0

gotch你。谢谢。 – Cannon 2011-06-18 06:56:34

你可以做到这一点使用System.IO.BinaryWriter接受一个流这样:

var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate); 
bw.Write(byteArray); 

有一个静态方法System.IO.File.WriteAllBytes

您可以使用FileStream.Write(byte[] array, int offset, int count)方法写出来。

如果你的数组名称是“myArray”,代码将会是。

myStream.Write(myArray, 0, myArray.count); 

public ActionResult Document(int id) 
    { 
     var obj = new CEATLMSEntities().LeaveDocuments.Where(c => c.Id == id).FirstOrDefault(); 
     string[] stringParts = obj.FName.Split(new char[] { '.' }); 
     string strType = stringParts[1]; 
     Response.Clear(); 
     Response.ClearContent(); 
     Response.ClearHeaders(); 
     Response.AddHeader("content-disposition", "attachment; filename=" + obj.FName); 
     var asciiCode = System.Text.Encoding.ASCII.GetString(obj.Document); 
     var datas = Convert.FromBase64String(asciiCode.Substring(asciiCode.IndexOf(',') + 1)); 
     //Set the content type as file extension type 
     Response.ContentType = strType; 
     //Write the file content 
     this.Response.BinaryWrite(datas); 
     this.Response.End(); 
     return new FileStreamResult(Response.OutputStream, obj.FType); 
    } 

尝试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; 
}