Umesha Gunasinghe
Umesha Gunasinghe

Reputation: 779

How to upload and read a CSV file in ASP.NET MVC3

I am working on a project and I need to upload a CSV file and read it. I am working in Visual Studio 2010 and MVC3 and C# language.

If I am to use html fileuplaod control, how I am suppose to take the uploaded file and read it in the client side itself without saving the file in the server. Do I have to use the jquery? I have searched but did not get solution to meet my requirements. I am new to MVC3 and CSV file handling and quite confused.

*What is the easiest way to upload a .csv file and read it in order to save it in the database.

A clear solution would be highly appreciated.Thanks.

Upvotes: 7

Views: 14946

Answers (3)

ske57
ske57

Reputation: 607

    private async Task<string> ProcessAsync(string surveyId)
    {           if(!Request.Content.IsMimeMultipartContent())
        {
            return "|UnsupportedMediaType";
        }

        try
        {
            var provider = new MultipartMemoryStreamProvider();

            await Request.Content.LoadIntoBufferAsync().ConfigureAwait(false);
            await Request.Content.ReadAsMultipartAsync(provider).ConfigureAwait(false);

            HttpContent content = provider.Contents.FirstOrDefault();

            if(content != null)
            {
                Stream stream = await content.ReadAsStreamAsync().ConfigureAwait(false);

                using (StreamReader CsvReader = new StreamReader(stream))
                {
                    string inputLine = "";

                    while ((inputLine = CsvReader.ReadLine()) != null)
                    {
                        string[] vars = inputLine.Split(',');


                    }
                    CsvReader.Close();
                    //return values;
                }

            }
        }
        catch(Exception e)
        {
            return e.ToString();
        }

        return "Nothing To Process";
 }

Upvotes: 0

Jon Spokes
Jon Spokes

Reputation: 2599

You should be able to access the data without saving it - using the InputStream property

http://msdn.microsoft.com/en-us/library/system.web.httppostedfile.inputstream.aspx

and this (see Paulius Zaliaduonis answer)

Upvotes: 2

Bhavik Goyal
Bhavik Goyal

Reputation: 2796

What you can do is save the file on server, then after you read the content from them you can delete the file.

I think there is a no way you can read the from client side. You must upload it on ur server to read that.

using (StreamReader CsvReader = new StreamReader(input_file))
                {
                    string inputLine = "";

                    while ((inputLine = CsvReader.ReadLine()) != null)
                    {
                        values.Add(inputLine.Trim().Replace(",", "").Replace(" ", ""));
                    }
                    CsvReader.Close();
                    return values;
                }

Upvotes: 4

Related Questions