Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Illegal characters in path c# error

Tags:

c#

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();
like image 760
creator Avatar asked Apr 28 '11 08:04

creator


4 Answers

The parameters are inverted. Do it as follows:

File.WriteAllText(sPath,sw.ToString());
like image 134
HCL Avatar answered Oct 07 '22 13:10

HCL


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());
like image 41
Graham Clark Avatar answered Oct 07 '22 13:10

Graham Clark


The call to

File.WriteAllText(sw.ToString(), sPath);

has the wrong parameter order. It should be

File.WriteAllText(sPath, sw.ToString());
like image 33
PVitt Avatar answered Oct 07 '22 15:10

PVitt


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);
like image 35
QuickDanger Avatar answered Oct 07 '22 15:10

QuickDanger