6

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();
1
  • The error I am getting is "Illegal characters in path" Commented Apr 28, 2011 at 8:15

5 Answers 5

15

The parameters are inverted. Do it as follows:

File.WriteAllText(sPath,sw.ToString());
Sign up to request clarification or add additional context in comments.

Comments

5

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());

Comments

4

The call to

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

has the wrong parameter order. It should be

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

Comments

2

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);

Comments

-1

The issue is probably a security related one. Your webpage wouldn't be default have access to the E drive.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.