[英]Byte array written to isolated storage area file in C# Windows Phone 7 app is invalid
[英]Can a Byte[] Array be written to a file in C#?
我正在嘗試將表示完整文件的Byte[]
數組寫入文件。
來自客戶端的原始文件通過 TCP 發送,然后由服務器接收。 接收到的流被讀取到一個字節數組,然后發送給這個類進行處理。
這主要是為了保證接收TCPClient
為下一個流做好准備,將接收端和處理端分開。
FileStream
類不將字節數組作為參數或另一個 Stream 對象(它允許您向其中寫入字節)。
我的目標是通過與原始線程(帶有 TCPClient 的線程)不同的線程來完成處理。
我不知道如何實現這一點,我應該嘗試什么?
基於問題的第一句話: “我正在嘗試將表示完整文件的 Byte[] 數組寫入文件。”
阻力最小的路徑是:
File.WriteAllBytes(string path, byte[] bytes)
記錄在這里:
您可以使用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
您可以使用System.IO.BinaryWriter
來執行此操作,它采用 Stream ,因此:
var bw = new BinaryWriter(File.Open("path",FileMode.OpenOrCreate);
bw.Write(byteArray);
您可以使用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 用戶提供對配置文件文件夾的訪問權限。
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.