Just want to share this code I used when uploading a file. I need to read a CSV file and save the data on a database.
First off, of course, is to add a file upload function in my page. I used the following syntax in my page, then code everything else.
So that's it. Just want to take some notes so that I won't forget this. he he
First off, of course, is to add a file upload function in my page. I used the following syntax in my page, then code everything else.
<asp:FileUpload ID="fuCSVFile" runat="server" />Then in my source code, when click button event is being called, my page will save the file in another folder. Then call a function to process the import to database.
<asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" />
void btnUpload_Click (object sender, EventArgs e){Everything worked fine, until when I tried importing a CSV file, which is around 6MB. I always get a connection timeout error. My colleague told me to check the maximum file size that ASP.NET allows. And there it is, by default, ASP.NET only permits files with at most 4MB file size. So I researched again for the solution and found this handy solution. This should be put in the Web.config file.
.
.
.
String Name = "Import_" + System.DateTime.Now.ToLongDateString().Replace(" ", "").Replace("/", "").Replace(":", "").Replace(".", "");
HttpPostedFile hpfCSV = fuCSVFile.PostedFile;
String textFile = HttpContext.Current.Request.MapPath("../" + Name + ".csv");
if (hpfCSV.ContentLength != 0)
{
hpfCSV.SaveAs(textFile);
ImportFromCSV(textFile);
}
.
.
.
}
void ImportFromCSV(String csvFile)
{
StreamReader sr = new StreamReader(CSVFile);
ArrayList values = new ArrayList();
// reading each line of the file
while (!sr.EndOfStream)
{
string[] val = null;
string fields = sr.ReadLine();
if (!fields.Contains("Artikelnummer"))
{
fields = fields.Replace("\"", ""); //remove all double quotes
// split each field
// delimiters depend on what is used in the CSV file.
// mine was a semi-colon
val = fields.Split(new char[] { ';' });
values.Add(val); //save the array of strings to an arraylist
}
}
foreach (string[] v in values)
{
//...
// import each array as one entry in the database
// we may call another function for the import to database
//...
}
}
<configuration>Anyway, if you want this setting to all of your workstations, or all of your web pages in your PC, then put this in your Machine.config, which is located in the \System Root\Microsoft.NEt\Framework\Version Number\CONFIG.
<system.web>
<httpRuntime executionTimeout="90" maxRequestLength="7168"
useFullyQualifiedRedirectUrl="false" minFreeThreads="8"
minLocalRequestFreeThreads="4" appRequestQueueLimit="100" />
</system.web>
</configuration>
So that's it. Just want to take some notes so that I won't forget this. he he
No comments:
Post a Comment