public void CreateFileOutput(object parameter)
{
string workSheetName, targetFile;
workSheetName = "data"; targetFile = "data.csv";
string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + SourceAppFilePath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';";
OleDbConnection conn = null;
StreamWriter wrtr = null;
OleDbCommand cmd = null;
OleDbDataAdapter da = null;
try
{
conn = new OleDbConnection(strConn);
conn.Open();
cmd = new OleDbCommand("SELECT * FROM [" + workSheetName + "$]", conn);
cmd.CommandType = CommandType.Text;
wrtr = new StreamWriter(targetFile);
da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
for (int x = 0; x < dt.Rows.Count; x++)
{
string rowString = "";
for (int y = 0; y < dt.Columns.Count; y++)
{
rowString += "\"" + dt.Rows[x][y].ToString() + "\",";
}
wrtr.WriteLine(rowString);
}
Console.WriteLine();
Console.WriteLine("Done! Your " + SourceAppFilePath + " has been converted into " + targetFile + ".");
Console.WriteLine();
}
catch (Exception exc)
{
Console.WriteLine(exc.ToString());
Console.ReadLine();
}
finally
{
if (conn.State == ConnectionState.Open)
conn.Close();
conn.Dispose();
cmd.Dispose();
da.Dispose();
wrtr.Close();
wrtr.Dispose();
}
}
XLS file is being converted to csv.I am able to see that in the for loop wrtr.WriteLine(rowString);
But I want to see the final output file “Data.csv” in the desktop location as I am taking the source .xls file from the desktop. Provide me a solution. Thanks.
You need to use the full path to save the file to the desktop. You can get the path using the
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory, like this:Then use FileStream with the full path:
Edited Per Comments Below
The key to this is specifying the path to where you want to save the file. Just giving a file name will put it in the directory the application is excuting from. An easy way to do this would be to use the
GetDirectoryNamemethod of thePathclass. Assuming the file was passed in, read from a config file, hard coded, etc:string path = Path.GetDirectoryName(sourceFile);
string target = path + @”\” + “Data.csv”;
If the sourceFile was C:\Data\Input.xml, then path would equal “C:\Data”, and target would be C:\Data\Data.csv.
The advantage here is that you can pass a filename with the path, and it will always place the targetfile in the same location. This lends itself nicely to parameterization of the method, or maybe even having the user select the file through an OpenFileDialog box or similar mechanism.
Additional Edit Per John’s Comment
Based on the code you posted, the Data.xsl file is in the executing application’s folder. In that case, you’d simply need to do the following:
No need to mess with paths, as the filestream will also go to the executing application’s directory.
In the end, it’s all about using the information available from the sourcefile (i.e., it’s location/path data) and applying it to the target file’s full path and name.