【问题标题】:Writing data to App_Data将数据写入 App_Data
【发布时间】:2010-04-04 13:54:26
【问题描述】:

我想使用以下代码将 .xml 文件写入 App_Data/posts。为什么会导致错误?

代码

 Stream writer  = new FileStream("..'\'App_Data'\'posts'\'" + new Guid(post_ID.ToString()).ToString() + ".xml", FileMode.Create);

【问题讨论】:

  • 请您写下您面临的错误

标签: .net asp.net file-io


【解决方案1】:

请发布您遇到的异常;不仅仅是“它不起作用”——这可能是各种各样的问题。以下是一些需要检查的事项:

检查 ASP.NET 进程是否对该目录具有写入权限。

另外,您似乎在错误地转义路径中的退格键。在使用 ASP.NET 时,您的路径应该是相对于应用程序根目录的。试试这个:

string path = HttpContext.Current.Server.MapPath("~/App_Data/posts/" + new Guid(post_ID.ToString()).ToString() + ".xml"
Stream writer  = new FileStream(path, FileMode.Create);

最后,确保帖子目录存在——否则文件创建将失败。

【讨论】:

  • 如何检查 ASP.NET 对该目录有写权限?
  • 它还说我没有 MapPath 的定义,因此 MapPath 带有下划线
  • 首先,您可以检查您得到的异常是否是 UnauthorizedException - 在这种情况下,它是权限问题。您得到的异常应该与您的问题一起发布。如果是权限问题,请使用 Windows 资源管理器为 App_Data 文件夹的 IIS_WPG 组授予读/写访问权限。
【解决方案2】:

删除多余的单引号并正确转义反斜杠。

或者更好的是,使用Server.MapPath(在 Page 和 UserControl 基类以及 HttpContext 等中可用)。

Server.MapPath("~/App_Data/posts/" + new Guid(post_ID.ToString()).ToString() + ".xml")

出于好奇,post_ID 的类型是什么?你为什么要把它转换成一个字符串,然后转换成一个 guid,然后再转换成一个字符串?

【讨论】:

    【解决方案3】:

    以上答案很好,但是它们依赖于 System.Web 程序集。

    如果您在库中创建文件创建方法,则 Server.MapPath 将不可用。

    在这种情况下,您甚至可以使用更通用的说法将数据写入 App_Data 文件夹

    我们使用 App_data 文件夹是因为黑客无法通过 http/https url 访问 app_data 文件夹中的文件(例如 http://yourwebsite.com/app_data/test.xml

                var rootDirectory = AppDomain.CurrentDomain.BaseDirectory;
                var folderNameToBecreated = "posts"; //
                var finalDirectoryPath = System.IO.Path.Combine(rootDirectory, "App_Data", folderNameToBecreated);
                var filename = Guid.NewGuid().ToString() + ".txt";
    
                //Create Directory if not exists
                if (System.IO.Directory.Exists(finalDirectoryPath) == false)
                {
                    System.IO.Directory.CreateDirectory(finalDirectoryPath);
                }
    
                var fullFilePath = System.IO.Path.Combine(finalDirectoryPath, filename);
                //testing your written file
                using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fullFilePath, true))
                {
                    sw.WriteLine("This is a test file");
                }
    

    【讨论】:

      猜你喜欢
      • 2016-09-07
      • 2010-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 2010-12-04
      • 1970-01-01
      相关资源
      最近更新 更多