我用写作下面的示例代码和下载内存流在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();
我收到以下错误:
指定参数超出有效值的范围。
参数名:偏移
可能是什么原因?
在你的代码,你将数据复制到阵列中的点,在TextWriter的可能没有刷新数据。 这将()发生在你的flush()或当您关闭它。
看看这个工程:
MemoryStream memoryStream = new MemoryStream();
TextWriter textWriter = new StreamWriter(memoryStream);
textWriter.WriteLine("Something");
textWriter.Flush(); // added this line
byte[] bytesInStream = memoryStream.ToArray(); // simpler way of converting to array
memoryStream.Close();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("content-disposition", "attachment; filename=name_you_file.xls");
Response.BinaryWrite(bytesInStream);
Response.End();
您在这里逻辑做错了什么。 首先,你写一些文字到MemoryStream
,然后你写一个空数组到同流。 我假设你正在试图流的内容复制到bytesInStream
阵列。 您可以通过调用创建数组memoryStream.ToArray()
或者,可以通过直接将数据写入流,以避免阵列复制的响应输出流使用MemoryStream.CopyTo
。 更换你BinaryWrite
使用该调用:
memoryStream.Position = 0;
memoryStream.CopyTo(Response.OutputStream);
注:该流在开始明确定位,因为CopyTo
将当前位置复制。
OK,既然一个明显得到downvoted提供只是一个工作的例子,让我解释:
首先,你不这样做
textWriter.Flush()
并期望的TextWriter的内容已经被刷新到的MemoryStream。
然后,你不这样做
memoryStream.Position = 0
并期望从位置0将MemoryStream被“写”。
然后,你做
memoryStream.Write(bytesInStream, 0, bytesInStream.Length);
但实际上你的意思是
memoryStream.Read(bytesInStream, 0, CInt(memoryStream.Length))
你也错过了长度很长,而读操作使用一个整数,这样你就可以得到一个异常那里。
因此,这是你的代码最小修改为“工作”(我它复制到VB工程)
Imports System.Web
Imports System.Web.Services
Public Class TextHandler
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
'context.Response.ContentType = "text/plain"
'context.Response.Write("Hello World!")
Dim memoryStream As New System.IO.MemoryStream()
Dim textWriter As System.IO.TextWriter = New System.IO.StreamWriter(memoryStream)
textWriter.WriteLine("Something")
textWriter.Flush()
memoryStream.Position = 0
Dim bytesInStream As Byte() = New Byte(memoryStream.Length - 1) {}
'memoryStream.Write(bytesInStream, 0, bytesInStream.Length)
memoryStream.Read(bytesInStream, 0, CInt(memoryStream.Length))
memoryStream.Close()
context.Response.Clear()
context.Response.ContentType = "application/force-download"
context.Response.AddHeader("content-disposition", "attachment; filename=name_you_file.txt")
context.Response.BinaryWrite(bytesInStream)
context.Response.End()
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
然后使用
Content-Type: application/force-download
意思是
“我,web服务器,我要骗你(浏览器),这个文件是什么,所以你不会把它作为一个PDF / Word文档/ MP3 /不管,并提示用户保存神秘的文件保存到磁盘代替”。 这是一个肮脏的黑客打破可怕的,当客户端没有做“保存到磁盘”。
...
最后,你不正确编码的文件名,所以如果使用非ASCII字符的文件名,它会断章取义的文件名,这是非常有趣的,如果你恰巧是中国或俄罗斯和完全ASCII字符集之外运行。
原版的
这里一个快速摘自我的ajax处理程序之一。 这是VB.NET,转换时,采取了长-1后事。
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim strFileName As String = "Umzugsmitteilung.doc"
Dim strUID As String = context.Request.QueryString("ump_uid")
context.Response.Clear()
'If String.IsNullOrEmpty(strUID) Or fileData Is Nothing Then
' context.Response.Write("<script type=""text/javascript"">alert('File does not exist !')</script>")
' context.Response.End()
'End If
context.Response.ClearContent()
'context.Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName)
context.Response.AddHeader("Content-Disposition", GetContentDisposition(strFileName))
'context.Response.ContentType = "application/msword"
context.Response.ContentType = "application/octet-stream"
GetUmzugsMitteilung(strUID)
context.Response.End()
End Sub ' ProcessRequest
Public Shared Sub SaveWordDocumentToOutputStream(strUID As String, doc As Aspose.Words.Document)
Using ms As System.IO.MemoryStream = New System.IO.MemoryStream()
CreateWordDocumentFromTemplate(strUID, doc, ms)
ms.Position = 0
Dim bytes As Byte() = New Byte(ms.Length - 1) {}
ms.Read(bytes, 0, CInt(ms.Length))
System.Web.HttpContext.Current.Response.OutputStream.Write(bytes, 0, ms.Length)
ms.Close()
End Using ' ms
End Sub ' SaveWordDocumentToOutputStream
Public Shared Function StripInvalidPathChars(str As String) As String
If str Is Nothing Then
Return Nothing
End If
Dim strReturnValue As String = ""
Dim strInvalidPathChars As New String(System.IO.Path.GetInvalidPathChars())
Dim bIsValid As Boolean = True
For Each cThisChar As Char In str
bIsValid = True
For Each cInvalid As Char In strInvalidPathChars
If cThisChar = cInvalid Then
bIsValid = False
Exit For
End If
Next cInvalid
If bIsValid Then
strReturnValue += cThisChar
End If
Next cThisChar
Return strReturnValue
End Function ' StripInvalidPathChars
Public Shared Function GetContentDisposition(ByVal strFileName As String) As String
' http://stackoverflow.com/questions/93551/how-to-encode-the-filename-parameter-of-content-disposition-header-in-http
Dim contentDisposition As String
strFileName = StripInvalidPathChars(strFileName)
If System.Web.HttpContext.Current IsNot Nothing AndAlso System.Web.HttpContext.Current.Request.Browser IsNot Nothing Then
If (System.Web.HttpContext.Current.Request.Browser.Browser = "IE" And (System.Web.HttpContext.Current.Request.Browser.Version = "7.0" Or System.Web.HttpContext.Current.Request.Browser.Version = "8.0")) Then
contentDisposition = "attachment; filename=" + Uri.EscapeDataString(strFileName).Replace("'", Uri.HexEscape("'"c))
ElseIf (System.Web.HttpContext.Current.Request.Browser.Browser = "Safari") Then
contentDisposition = "attachment; filename=" + strFileName
Else
contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(strFileName)
End If
Else
contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(strFileName)
End If
Return contentDisposition
End Function ' GetContentDisposition
您正在使用一个很长的路字符串转换为字节。
你确定,你需要的任何数据流? 为什么就是不使用编码?
Response.BinaryWrite(Encoding.UTF8.GetBytes("Something"))