I am getting the error
Illegal characters in path
for the code below . Please help me out.
response.Clear();
response.Charset = "";
Response.ContentEncoding = System.Text.Encoding.Default;
// set the response mime type for excel
response.ContentType = "application/vnd.ms-excel";
string sFileName = "Testeeeeee.xls";
response.AddHeader("Content-Disposition", "attachment;filename=\"" + sFileName + "\"");
// create a string writer
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter htw = new HtmlTextWriter(sw))
{
// instantiate a datagrid
DataGrid dg = new DataGrid();
dg.DataSource = DS.Tables[0];
dg.DataBind();
dg.RenderControl(htw);
string sPath = @"E:\CR-12\Test.xls";
File.WriteAllText(sw.ToString(), sPath);// I get the error at this line
response.End();
The parameters are inverted. Do it as follows:
File.WriteAllText(sPath,sw.ToString());
You've got the parameters to File.WriteAllText
mixed up. The first one is the path, the second is the contents. You need
File.WriteAllText(sPath, sw.ToString());
The call to
File.WriteAllText(sw.ToString(), sPath);
has the wrong parameter order. It should be
File.WriteAllText(sPath, sw.ToString());
For others receiving this error, make sure you are using backslashes correctly since they are also escape characters. A single backslash can result in this error. Use 2 backslashes to properly output a single escaped backslash.
Ex:
System.IO.File.WriteAllText("C:\\file.txt", output);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With