Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert CSV from file upload control directly to memory stream without physical path

I am not sure if this is possible so it would be nice to have some help.

What I want to do is use a fileupload control in asp.net to select a csv file. Then use my submit button on the page to run my server side code which will take that csv file and put it into memory stream where it will be parsed and then added to collection object.

I do know it's easier to save the csv file to a physical path and then do some kind of cleanup where I delete the file but if possible I would like to do it this way.

See below for code so far:

protected void btnUpload_Click(object sender, EventArgs e)
    {
        string connectingString = "";
        if (ctrlFileUpload.HasFile)
        {
            string fileName =
                Path.GetFileName(ctrlFileUpload.PostedFile.FileName);

            string fileExtension =
                Path.GetExtension(ctrlFileUpload.PostedFile.FileName);

            ReadCsv(fileName);
        }
    }

protected void ReadCsv(string fileName)
    {
        // Some logic for parsing csv file in memory stream
    }
}

Any ideas? Thanks!

like image 844
nick gowdy Avatar asked Dec 28 '25 16:12

nick gowdy


1 Answers

I know this is an old question, but the below code will work for reading your posted text file into a memory stream using a StreamReader and is compatible with .NET 4.0:

protected void ReadCsv()
{
    StreamReader reader = new StreamReader(ctrlFileUpload.PostedFile.InputStream);
    string content = reader.ReadToEnd();
}

Note, this method is only efficient if you have enough memory on the server to handle larger files for multiple users concurrently. You don't want to use this approach if you have hundreds of users posting files simultaneously to a memory stream and causing your server to crash due to insufficient available memory. You'll also want to check if this is an acceptable method if you're on a shared hosting environment.

like image 87
Cameron Tinker Avatar answered Dec 31 '25 17:12

Cameron Tinker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!