简体   繁体   中英

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. when I added these two lines var outFilePath = @"F:\\BI\\Out\\" + Path.GetFileName(file); 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. 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:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM