路径c#错误中的非法字符

时间:2011-04-28 08:13:33

标签: c#

我收到错误

  

路径中的非法字符

代码如下。请帮帮我。

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

5 个答案:

答案 0 :(得分:10)

parameters被倒置了。这样做:

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

答案 1 :(得分:5)

你有File.WriteAllText的参数混淆了。第一个是路径,第二个是内容。你需要

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

答案 2 :(得分:4)

致电

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

参数顺序错误。它应该是

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

答案 3 :(得分:2)

对于接收此错误的其他人,请确保正确使用反斜杠,因为它们也是转义字符。单个反斜杠可能会导致此错误。使用2个反斜杠正确输出单个转义反斜杠。

例如:

System.IO.File.WriteAllText("C:\\file.txt", output);

答案 4 :(得分:-1)

问题可能与安全相关。您的网页不会默认有权访问E盘。