Reputation: 61
I am working with a project in which I need to compare the byte representation of the file being uploaded to go ahead and check it against an accepted file size.
However, when the compiler executes byte[ ] filebyte = fileUpload.FileBytes
the StreamReader
stops functioning correctly.
Why is this behavior being caused, and is there a better way to accomplish what I am trying to do?
Below is a sample mockup of the issue.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileUpload.aspx.cs" Inherits="TestASP.FileUpload" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></ajax:ToolkitScriptManager>
<ajax:AsyncFileUpload runat="server" ID="fileUpload" Width="300px" UploaderStyle="Modern"
BackColor="LightCoral" UploadingBackColor="#CCFFFF" ThrobberID="fileLoader" />
<asp:Button ID="btUpload" runat="server" Text="Upload" OnClick="btUpload_Clicked" />
<br />
<asp:Label ID="lblMessage" runat="server" ForeColor="Green"></asp:Label>
<br />
<asp:Label ID="lblError" runat="server" ForeColor="Red"></asp:Label>
</div>
</form>
</body>
</html>
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
}
protected void btUpload_Clicked(object sender, EventArgs e)
{
if(fileUpload.HasFile)
{
byte[] fileByte = fileUpload.FileBytes;
StreamReader sr = new StreamReader(fileUpload.FileContent);
TextReader tr = sr;
String fileContent = tr.ReadToEnd();
String fileName = Path.GetFileName(fileUpload.FileName);
this.lblMessage.Text = (fileContent);
}
else
{
this.lblError.Text = "File Not Uploaded";
}
}
Upvotes: 2
Views: 1269
Reputation: 22481
You should decide for one way or the other, either use FileBytes or open the Stream using the FileContent property. I assume that FileBytes also reads the content of the Stream, so the StreamReader will start reading at the end - hence the empty output.
If you only want to check the size, you can do this using the PostedFile.ContentLength property:
if(fileUpload.HasFile)
{
var sizeLimit = 1024 * 1024; // Limit to a megabyte
if (fileUpload.PostedFile.ContentLength > sizeLimit)
lblError.Tet = "File is too large";
else
{
using(StreamReader sr = new StreamReader(fileUpload.FileContent))
{
String fileContent = sr.ReadToEnd();
String fileName = Path.GetFileName(fileUpload.FileName);
this.lblMessage.Text = (fileContent);
}
}
}
Upvotes: 1