我使用StreamWriter
创建多个文件,我希望在特定目录中创建这些文件
StreamWriter w = new StreamWriter(File.Create(name + ".txt"));
w.WriteLine(name);
w.Close();
此处name
是变量,用作文件名,也可写入该文件,但我的问题是我希望在特定目录中创建此文件。
答案 0 :(得分:4)
Path.Combine
使用Path.PathSeparator
并检查第一个路径是否在末尾已有分隔符,因此不会复制分隔符。此外,它还会检查要组合的路径元素是否具有无效字符。
引用此SO post
检查name
变量是否包含文件名的无效字符也很有成效。
您可以先使用Path.GetInvalidFileNameChars方法从name
变量中删除无效字符:
var invalidChars = Path.GetInvalidFileNameChars();
string invalidCharsRemoved = new string(name
.Where(x => !invalidChars.Contains(x))
.ToArray());
引用此SO post
string directory = "c:\\temp";
而不是
File.Create(name + ".txt")
使用
string filename = invalidCharsRemoved + ".txt"
File.Create(Path.Combine(directory , filename ))
答案 1 :(得分:3)
您也可以包含路径:
string path = "C:\\SomeFolder\\";
File.Create( path + name + ".txt");
或使用Path.Combine
之类的:
File.Create( Path.Combine(path, name + ".txt") );
答案 2 :(得分:2)
之类的内容
name
包含@"U:\TDScripts\acchf122_0023"
好的,根据您评论中的新信息,您实际上需要摆脱旧的路径和目录。
您可以使用Path.GetFileNameWithoutExtension方法来实现这一目标。之后,您可以使用Path.Combine创建自己的路径。
以下是一个示例:
string myDirectory = @"C:\temp";
string oldPathWithName = @"U:\TDScripts\acchf122_0023";
string onlyFileName = Path.GetFileNameWithoutExtension(oldPathWithName);
string myNewPath = Path.Combine(myDirectory, onlyFileName + ".txt");
Console.WriteLine(myNewPath);
我希望这能解决你的问题。
答案 3 :(得分:1)
您可以为您的目录声明path
,如下所示:
string path = @"c:\folder\....";
然后使用以下命令:
File.Create( path + name + ".txt");
你会得到你想要的东西
答案 4 :(得分:1)
FileStream fileStream = null;
StreamWriter writer = null;
try
{
string folderPath = @"D:\SpecificDirecory\";
string path = Path.Combine(folderPath , "fileName.txt");
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
fileStream = new FileStream(@path, FileMode.Create);
writer = new StreamWriter(fileStream);
writer.Write(fileBuilder.ToString());
}
catch (Exception ex)
{
throw ex;
}
finally
{
writer.Close();
fileStream.Close();
}