[英]How do I save some files under a directory in a new directory after making some changes
I opened a directory and I read some files in that directory amd made some changes, now I want to save the changes with the same file names at F:\\BI\\Out\\ and keep the original files. 我打开了一个目录,并读取了该目录中的一些文件并进行了一些更改,现在我想使用相同的文件名将更改保存在F:\\ BI \\ Out \\并保留原始文件。 when I added these two lines var outFilePath = @"F:\\BI\\Out\\" + Path.GetFileName(file);
当我添加这两行时,var outFilePath = @“ F:\\ BI \\ Out \\” + Path.GetFileName(file); File.WriteAllText(outFilePath, text);
File.WriteAllText(outFilePath,text); I was able to save the files under the new folder\\Out, but when I opened them I found that only one file is changed correctly and all the other files the old words are replace by blank space not by the new words.
我能够将文件保存在新文件夹\\ Out下,但是当我打开它们时,我发现只有一个文件被正确更改,而所有其他文件的旧单词被空格替换而不是新单词。 Can anyone help me Thanks
谁能帮我谢谢
string text = "";
string[] files;
private void Form1_Load(object sender, EventArgs e)
{
try
{
files = Directory.GetFiles(@"F:\BI\In\", "*.*", SearchOption.AllDirectories);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
this.Close();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtEtlPath.Text == "")
{
MessageBox.Show("Please Enter path");
txtEtlPath.Focus();
}
else
{
foreach (string file in files)
{
if (System.IO.File.Exists(file))
{
text = File.ReadAllText(file);
text = text.Replace("Company_Address", txtCompanyAddress.Text + "_BI");
text = text.Replace("Company_Name", txtCompanyName.Text.Trim() + "_BIDW");
text = text.Replace("C:\\BIfolder",cboDrive.Text + txtEtlPath.Text.Trim());
var outFilePath = @"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
}
Within your foreach () loop: 在您的foreach()循环中:
If you want the subfolder structure of the files found, do a replace on the filepath: 如果要找到文件的子文件夹结构,请在文件路径上进行替换:
var outFilePath = file.Replace(@"F:\BI\In\", @"F:\BI\Out\");
You will need to create the subfolder before you can write the changed file: 您需要先创建子文件夹,然后才能写入更改的文件:
new FileInfo(outFilePath)).Directory.Create();
If you don't want the subfolders, you can write directly into the top folder: 如果不需要子文件夹,可以直接写入顶层文件夹:
var outFilePath = @"F:\BI\Out\" + Path.GetFileName(file);
Writing is simple, just keep in mind there is an optional encoding parameter: 编写很简单,请记住有一个可选的编码参数:
File.WriteAllText(outFilePath, text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.