我试图在内存中创建一个文本文件,添加一些行,最后将文件保存在文本文件中.我可以处理savedialog部分,但我不知道如何从内存中获取文本文件.任何帮助和提示都将受到关注.
到目前为止我所做的是:
//Initialize in memory text writer
MemoryStream ms = new MemoryStream();
TextWriter tw = new StreamWriter(ms);
tw.WriteLine("HELLO WORLD!");
tw.WriteLine("I WANT TO SAVE THIS FILE AS A .TXT FILE!);
Run Code Online (Sandbox Code Playgroud)
请注意 我将调用tw.WriteLine()在不同的地方添加更多行,所以我想在程序结束时保存它(所以这个主题应该包含在使用{}之类的东西中)
UPDATE
StringBuilder似乎是一个更可靠的选择!当我使用MemoryStream执行此操作时,我的文本文件中出现了奇怪的剪切.
谢谢.
使用sharpPDF库我生成一个pdf内存流,我想通过电子邮件直接发送它.但行ms.Seek(....给出一个ObjectDisposedException;
无法访问封闭的Stream.
pdf.CreatePDF方法接受(输出)fileName字符串或(out)Stream.但我想它也关闭了流?我不习惯在溪流上工作太多,所以如果你能告诉它应该怎么做?
可以在此处找到CreatePDF方法的sharpPDF源代码:
http://www.java2s.com/Open-Source/CSharp/PDF/SharpPDF/sharpPDF/pdfDocument.cs.htm
Public Sub SendPDF()
Dim pdf As New sharpPDF.pdfDocument("Title", "Author")
'....Generate pdf content
Dim ms As New IO.MemoryStream
pdf.CreatePDF(ms)
Dim email As New EmailService
email.Send(ms)
End Sub
Public Class EmailService
Public Sub Send(Byval ms as Stream)
ms.Seek(0, IO.SeekOrigin.Begin)
Dim atc As New Attachment(ms, "Report.pdf")
mail.Attachments.Add(atc)
'....set other email parameters
client.SendAsync(mail, mail.Subject)
End Sub
End Class
Run Code Online (Sandbox Code Playgroud) 现在我正在使用XmlTextWriter将MemoryStream对象转换为字符串.但我不知道是否有更快的方法将内存流序列化为字符串.
我按照此处给出的代码进行序列化 - http://www.eggheadcafe.com/articles/system.xml.xmlserialization.asp
编辑
流到字符串
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
string content = sr.ReadToEnd();
SaveInDB(ms);
}
Run Code Online (Sandbox Code Playgroud)
字符串到流
string content = GetFromContentDB();
byte[] byteArray = Encoding.ASCII.GetBytes(content);
MemoryStream ms = new MemoryStream(byteArray);
byte[] outBuf = ms.GetBuffer(); //error here
Run Code Online (Sandbox Code Playgroud) public ActionResult CustomChart(int reportID)
{
Chart chart = new Chart();
// Save the chart to a MemoryStream
var imgStream = new MemoryStream();
chart.SaveImage(imgStream);
imgStream.Seek(0, SeekOrigin.Begin);
// Return the contents of the Stream to the client
return File(imgStream, "image/png");
}
Run Code Online (Sandbox Code Playgroud)
我习惯于将"using"语句与MemoryStreams结合使用.这是不是必须使用'使用'语句的情况吗?或者在'using'语句中调用return是否有效?
编辑:
出于我的目的,我发现引入'using'语句不起作用(抛出ObjectDisposedException).这是我在客户端做的事情:
$('#ReportTest').bind('load', function () {
$('#LoadingPanel').hide();
$(this).unbind('load');
}).bind('error', function () {
$('#LoadingPanel').hide();
$(this).unbind('error');
}).attr('src', '../../Chart/CustomChart?ReportID=' + settings.id);
Run Code Online (Sandbox Code Playgroud) 我正在使用下面的示例代码来编写和下载内存流到C#中的文件.
MemoryStream memoryStream = new MemoryStream();
TextWriter textWriter = new StreamWriter(memoryStream);
textWriter.WriteLine("Something");
byte[] bytesInStream = new byte[memoryStream.Length];
memoryStream.Write(bytesInStream, 0, bytesInStream.Length);
memoryStream.Close();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition",
"attachment; filename=name_you_file.xls");
Response.BinaryWrite(bytesInStream);
Response.End();
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
指定的参数超出了有效值的范围.
参数名称:offset
可能是什么原因?
我从智能相机成像器捕获图像并通过套接字编程从相机接收字节数组(.NET应用程序是客户端,相机是服务器).
问题是我在运行时得到System.InvalidArgument异常.
private Image byteArrayToImage(byte[] byteArray)
{
if(byteArray != null)
{
MemoryStream ms = new MemoryStream(byteArray);
return Image.FromStream(ms, false, false);
/*last argument is supposed to turn Image data validation off*/
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
我在很多论坛上都搜索过这个问题并尝试过许多专家给出的建议,但没有任何帮助.
我不认为字节数组有任何问题,因为当我将相同的字节数组输入我的VC++ MFC客户端应用程序时,我得到了图像.但这在C#.NET中不起作用.
谁能帮我 ?
PS:
我试图完成同样任务的其他方法是:
1.
private Image byteArrayToImage(byte[] byteArray)
{
if(byteArray != null)
{
MemoryStream ms = new MemoryStream();
ms.Write(byteArray, 0, byteArray.Length);
ms.Position = 0;
return Image.FromStream(ms, false, false);
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
2.
private Image byteArrayToImage(byte[] byteArray)
{
if(byteArray != null)
{ …
Run Code Online (Sandbox Code Playgroud) 使用Open XML SDK v2.0创建Excel电子表格时,我们的Excel输出最初成功运行了几个月.最近Excel(所有版本)开始抱怨"Excel在'zot.xlsx'中找到了不可读的内容.你想恢复这个工作簿的内容吗?".我们使用MemoryStream作为存储在Web应用程序中创建文件,然后将其作为byte []发送到HTTP响应中,MIME类型为"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".坏文件的解压缩内容与没有错误的文件的解压缩内容相同.
bool MemoryStream.TryGetBuffer(out ArraySegment<byte> buffer)
是.NET 4.6中的一个新API,可用于访问存储在MemoryStream中的有效字节,而无需复制它们.这非常令人兴奋!它返回一个bool,如果转换成功则为"true;否则为false"并填充out参数.
什么时候返回true,表示out ArraySegment<byte> buffer
现在包含有效信息?今天没有记录.
我知道如果它返回false,我可以.ToArray()
用来获取字节的副本.并且,我们已经拥有.GetBuffer()
,但有时MemoryStreams是在缓冲区中创建的,并且这些信息很难(好吧,等等)以后再使用,更不用说try ... catch
稳健性所需了.
我ActionFilterAttribute
在按下控制器之前用来获取请求,如下所示:
public override void OnActionExecuting(HttpActionContext actionContext)
{
using (var stream = new MemoryStream())
{
HttpContextBase context = (HttpContextBase)actionContext.Request.Properties["MS_HttpContext"];
context.Request.InputStream.Seek(0, SeekOrigin.Begin);
context.Request.InputStream.CopyTo(stream);
requestBody = Encoding.UTF8.GetString(stream.ToArray());
}
}
Run Code Online (Sandbox Code Playgroud)
上面的方法适用于小的请求但是对于一个大的json,它给了我这个错误:
在HttpRequest.GetBufferedInputStream的调用者填充内部存储之前,访问了BinaryRead,Form,Files或InputStream.
输入流会出现此错误
context.Request.InputStream引发了System.InvalidOperationException类型的异常System.IO.Stream {System.InvalidOperationException}
正如我在研究中发现的那样,这是超时问题,但我无法更改代码中的超时.我试图改变这些值在web.config文件maxRequestLength="102400000"
和maxAllowedContentLength="209715100"
,但我仍面临着同样的错误.
如果我读了GetBufferedInputStream
但仍然是同一个问题,它只是读取缓冲区的一部分,而不是整个流.
我也试过以下:
Stream InStream;
int Len;
InStream = HttpContext.Current.Request.InputStream;
Len = System.Convert.ToInt32(InStream.Length);
byte[] ByteArray = new byte[Len + 1];
InStream.Seek(0, SeekOrigin.Begin);
InStream.Read(ByteArray, 0, Len);
var jsonParam = System.Text.Encoding.UTF8.GetString(ByteArray);
Run Code Online (Sandbox Code Playgroud)
请注意,如果我设置内容类型application/xml
或application/x-www-form-urlencoded
它的工作原理,但是如果我将其设置为application/json
它会给我这个错误!!
请指教!
我有一个问题,我找不到理由.我正在创建一个自定义存档文件.我MemoryStream
用来存储数据,最后我用a FileStream
来将数据写入磁盘.
我的硬盘是SSD,但速度太慢了.当我尝试只向文件写入95 MB时,写入需要12秒!
我尝试了Filestream.Write
,File.WriteAllBytes
但它是一样的.
最后,我有了一个想法,复制它,它快了100倍!
我需要知道为什么会发生这种情况以及写入函数出了什么问题.
这是我的代码:
//// First of all I create an example 150MB file
Random randomgen = new Random();
byte[] new_byte_array = new byte[150000000];
randomgen.NextBytes(new_byte_array);
//// I turned the byte array into a MemoryStream
MemoryStream file1 = new MemoryStream(new_byte_array);
//// HERE I DO SOME THINGS WITH THE MEMORYSTREAM
/// Method 1 : File.WriteAllBytes | 13,944 ms
byte[] output = file1.ToArray();
File.WriteAllBytes("output.test", output);
// Method 2 …
Run Code Online (Sandbox Code Playgroud) memorystream ×10
c# ×7
.net ×3
asp.net ×1
asp.net-mvc ×1
excel ×1
exception ×1
filestream ×1
image ×1
inputstream ×1
jquery ×1
openxml ×1
openxml-sdk ×1
sharppdf ×1
textwriter ×1
using ×1
xml ×1