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

5

我在下面的代码中遇到了错误:

路径中有非法字符

请帮我解决这个问题。

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

我遇到的错误是“路径中有非法字符”。 - creator
5个回答

14

parameters被反转了。请按以下方式进行操作:

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

5
您将 File.WriteAllText 的参数弄混了。第一个参数是路径,第二个参数是内容。您需要:
File.WriteAllText(sPath, sw.ToString());

4

调用

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

参数顺序错误。正确的顺序应该是

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

2

如果其他人也遇到了这个错误,请确保您正确使用反斜杠,因为它们也是转义字符。一个单独的反斜杠可能导致此错误。请使用2个反斜杠来正确输出一个转义的反斜杠。

例如:

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

-1
问题可能与安全有关。您的网页默认情况下无法访问E驱动器。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接