3

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!

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Does this help?

This should give you the stream. So you'd make your ReadCsv method accept a reference to the stream, and pass that to it rather than the filename, and work against the stream.

MSDN FileUpload.FileContent Property

1 Comment

This doesn't really help because I don't want to save the file to a location. It's also in .NET 4.5, I am using 4.0.
0

//Try below one to capture data in MemoryStream from FileUpload Control

  protected void btnFileUpload_Click(object sender, EventArgs e)
    {
        if (FileUploadControl.HasFile)
        {
            try
            {                 
                #region Capture file data in Memory Stream

                byte[] fileData = null;
                Stream fileStream = null;
                int length = 0;

                length = FileUploadControl.PostedFile.ContentLength;
                fileData = new byte[length + 1];
                fileStream = FileUploadControl.PostedFile.InputStream;
                fileStream.Read(fileData, 0, length);

                //Use MemoryStream to capture file data
                MemoryStream stream = new MemoryStream(fileData);

                Session["FileUploaded"] = stream;

                #endregion

                StreamReader strFile;                 

                using (strFile = new StreamReader(stream))
                {
                    string line;
                    DataTable dtStudentData = CreateDataTable();
                    DataRow drStudentRow;
                    List<String> errorMessages = new List<String>();
                    // Read and display lines from the file until the end of the file is reached. 
                    while ((line = strFile.ReadLine()) != null)
                    {
                        if (line.Trim().Length > 0)
                        {
                            System.Threading.Thread.Sleep(1000);
                            string[] columns = line.Split('\t'); //splitting the line which was read by the stream reader object                                  

                            Int32 charpos = (Int32)strFile.GetType().InvokeMember("charPos", BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField, null, strFile, null);

                            Int32 charlen = (Int32)strFile.GetType().InvokeMember("charLen",
                            BindingFlags.DeclaredOnly |
                            BindingFlags.Public | BindingFlags.NonPublic |
                            BindingFlags.Instance | BindingFlags.GetField
                             , null, strFile, null);

                            int lineno = (Int32)strFile.BaseStream.Position - charlen + charpos;                                

                            //Add data row in Data Table
                            drStudentRow = dtStudentData.NewRow();  
                            // TO DO code - Fill data table
                            dtStudentData.Rows.Add(drStudentRow);
                        }                            
                    }
                    strFile.Dispose();
                    dtStudentData.Rows.RemoveAt(0); //Remove the first column since its the column name not necessary to insert in the database table
                    PopulateStudentInvalidDataGridView(dtStudentData);    // Bind Grid                    
                    Session["StudentData_FileParsedStudentRegistrtaionTable"] = dtStudentData;
                    strFile.Close(); //release the stream reader                        
                }
            }
            catch (Exception ex)
            {
                String error = ex.Message;
            }
        }
    }       

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.