[英]StreamWriter to project directory and sub directory?
I'm currently having an issue with my application and I'm starting to think it's just my logic. 我目前的应用程序存在问题,我开始认为这只是我的逻辑。 I can't figure it out even after browsing these forms and MSDN. 在浏览这些表格和MSDN之后,我无法弄明白。
I'm trying to use StreamWriter to create a text document in my app directory and create sub folder containing that document. 我正在尝试使用StreamWriter在我的app目录中创建一个文本文档,并创建包含该文档的子文件夹。 Currently it just keeps dumping the file in my apps exe directory. 目前它只是将文件转储到我的apps exe目录中。
string runTimeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string recipeDirectory = Path.Combine(runTimeDirectory, "Recipes");
if (!Directory.Exists(recipeDirectory))
{
//Recipes directory doesnt exist so create it
Directory.CreateDirectory(recipeDirectory);
}
// Write text to file
using (StreamWriter OutputFile = new StreamWriter(recipeDirectory + RecipeName + @".txt"))
{
Try this: 尝试这个:
using (StreamWriter OutputFile = new StreamWriter(
Path.Combine(recipeDirectory, RecipeName + @".txt")))
The reason I think is that your recipeDirectory
and RecipeName + @".txt"
aren't separated by the backslash, so the file is written to the parent directory instead and named recipeDirectory + RecipeName + @".txt"
. 我认为你的recipeDirectory
和RecipeName + @".txt"
没有用反斜杠分隔,所以该文件被写入父目录,并命名为recipeDirectory + RecipeName + @".txt"
。
As an aside, I would also recommend you pass your RecipeName
through a sanitizer function like this in case any name contains characters that can't be used in a file name: RecipeName
一句,我还建议您通过这样的清理程序函数传递RecipeName
,以防任何名称包含无法在文件名中使用的字符:
internal static string GetSafeFileName(string fromString)
{
var invalidChars = Path.GetInvalidFileNameChars();
const char ReplacementChar = '_';
return new string(fromString.Select((inputChar) =>
invalidChars.Any((invalidChar) =>
(inputChar == invalidChar)) ? ReplacementChar : inputChar).ToArray());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.