shradha
shradha

Reputation: 147

is there a way to query a stream in c#, ex. select * from a streamobject

I have a file upload control in my asp.net (c#) website, which is used to upload csv files with data to be inserted into the database, my problem is that, I was not able to get the actual path of the uploaded file

It always gave me: C:\inetput\projectfolder\csvname.csv where it should have been similar to: C:\Documents and settings\Pcname\Desktop\csvname.csv

but by going through the various post of file upload, i came to know that file need to be saved on the server first,

using Fileupload1.Saveas(savepath);

which is mandatory to save the file in a previously specified location, where this not actually required. (since it will increase the overhead of again deleting the file).

then what I do is as below:

bool result = true;
strm = FileUpload1.PostedFile.InputStream;

reader2 = new System.IO.StreamReader(strm);

// **** new ****

FileInfo fileinfo = new FileInfo(FileUpload1.PostedFile.FileName);


string savePath = "c:\\"; // example "c:\\temp\\uploads\\"; could be any path

string fileName = fileinfo.Name;
string strFilePath = savePath.ToString();


savePath += fileName;

FileUpload1.SaveAs(savePath);

string strSql = "SELECT * FROM [" + fileinfo.Name + "]";

string strCSVConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFilePath + ";" + "Extended Properties='text;HDR=NO;'";

// load the data from CSV to DataTable 

OleDbDataAdapter oleda = new OleDbDataAdapter(strSql, strCSVConnString);

DataTable dtbCSV = new DataTable();

oleda.Fill(dtbCSV);

if (dtbCSV.Columns.Count != 2)
{
    result = false;
}

because I want to count the number of columns in the file, I'm using the oledb reader. which needs a file to be queried.

Is it possible to Query a stream? I dont want to save the file, instead just read it without saving.

Upvotes: 4

Views: 1268

Answers (1)

Pablo Romeo
Pablo Romeo

Reputation: 11396

Unfortunately you cannot use OLEDB against a stream.

In situations where it is mandatory to use OLEDB I've managed to write an IDisposable wrapper that would provide a temporary file from a stream and manage deletion.

You could however go for an alternate approach to reading the contents, without saving it, such as parsing the file yourself directly from a stream. I would recommend this instead of the wrapper since you avoid file access restriction problems as well as the overhead of file access.

Here's an SO with several different approaches.

Upvotes: 1

Related Questions