C# StreamWriter到项目目录和子目录?
我目前的应用程序有问题,我开始认为这只是我的逻辑。即使浏览了这些表单和MSDN,我也无法理解 我正在尝试使用StreamWriter在我的应用程序目录中创建一个文本文档,并创建包含该文档的子文件夹。目前,它只是不断转储我的应用程序exe目录中的文件C# StreamWriter到项目目录和子目录?,c#,streamwriter,C#,Streamwriter,我目前的应用程序有问题,我开始认为这只是我的逻辑。即使浏览了这些表单和MSDN,我也无法理解 我正在尝试使用StreamWriter在我的应用程序目录中创建一个文本文档,并创建包含该文档的子文件夹。目前,它只是不断转储我的应用程序exe目录中的文件 string runTimeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string recipeDire
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"))
{
试试这个:
using (StreamWriter OutputFile = new StreamWriter(
Path.Combine(recipeDirectory, RecipeName + @".txt")))
我认为原因是您的recipeDirectory
和RecipeName+@.txt“
没有用反斜杠分隔,因此该文件被写入父目录,并命名为recipeDirectory+RecipeName+@.txt”
顺便说一句,我还建议您通过一个消毒剂函数传递您的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());
}
只是一个猜测,但是
recipeDirectory
可能不会以`结尾,因此您以:
C:\foo\Recpiesmyrecipe.txt`而不是:`C:\foo\Recipies\myrecipie.txt`结尾“没错,它正在创建文件+文件目录名。我在下面的答案中看到了我的问题。我也这么认为,但你会认为这很明显,因为创建的文件会有一个不可靠的名称。不是Path。Combine
为你这样做吗?@AlfieGoodacre是的,但OP没有使用它。这就是我的答案所补充的…@roryap哦,是的,对不起,我在他们的代码中读到了,所以我想那也在那里already@JosephOliveri不客气。我刚刚在我的答案中添加了一个(重要的)更新,供您审阅。