我希望使用以下代码将一个 .xml 文件写入 App_Data/posts 文件夹中。为什么会导致错误?
代码
Stream writer = new FileStream("..'\'App_Data'\'posts'\'" + new Guid(post_ID.ToString()).ToString() + ".xml", FileMode.Create);
string path = HttpContext.Current.Server.MapPath("~/App_Data/posts/" + new Guid(post_ID.ToString()).ToString() + ".xml"
Stream writer = new FileStream(path, FileMode.Create);
最后,请确保“posts”目录存在,否则文件创建将失败。
去掉多余的单引号并正确转义反斜杠。
或者更好的方法是使用Server.MapPath
(在Page和UserControl基类以及HttpContext等中可用)。
Server.MapPath("~/App_Data/posts/" + new Guid(post_ID.ToString()).ToString() + ".xml")
出于好奇,post_ID是什么类型?为什么要将它转换为字符串,然后再转换为guid,最后又转回字符串?
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");
}