简体   繁体   English

覆写档案只能运作一次

[英]Overwrite file only works once

I have a simple program that copies files and directories from one place to another. 我有一个简单的程序,可以将文件和目录从一个地方复制到另一个地方。 I have it set-up that if there are any exceptions (such as if access to the path is denied) it will create a log file with the error. 我进行了设置,如果有任何异常(例如,如果拒绝访问路径),它将创建一个错误日志文件。

I have a button that when pressed, performs the copy action. 我有一个按钮,按下该按钮即可执行复制操作。 Everything works fine the first time I press the button and the log file is either created or overwritten with the appropriate error messages. 第一次按下按钮,一切正常,日志文件被创建或被相应的错误消息覆盖。

However, if I press the button a second time, the text file is not overwritten and instead the error messages append. 但是,如果我第二次按下按钮,则文本文件不会被覆盖,而是会附加错误消息。 If I close out of my program and run it again, the file is overwritten on the first button press. 如果我关闭程序并再次运行它,则在第一次按下按钮时文件就会被覆盖。 Any thoughts would be greatly appreciated. 任何想法将不胜感激。

target is a string filepath which I'm getting from a FolderBrowserDialog and taking the selected path and setting it to a textbox. target是一个字符串文件路径,它是从FolderBrowserDialog获取的,并采用了选定的路径并将其设置为文本框。 loglist is just a simple List<string> I'm using to store the error messages from any exceptions that occur during the copy process. loglist只是一个简单的List<string>用于存储复制过程中发生的任何异常的错误消息。

public partial class Form1 : Form
{

    static List<string> logList = new List<string>();

    public Form1()
    {
        InitializeComponent();
    }


    private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
    {


        if (source.FullName.ToLower() == target.FullName.ToLower())
            return;

        if (Directory.Exists(target.FullName) == false)
        {
            Directory.CreateDirectory(target.FullName);
        }





        foreach (FileInfo fi in source.GetFiles())
        {
            try
            {
                fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
            }
            catch (Exception ex)
            {
                logList.Add(ex.Message);


            }


        }

        foreach (DirectoryInfo diSourceSub in source.GetDirectories())
        {
            DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSub.Name);
            CopyAll(diSourceSub, nextTargetSubDir);

        }



    }


    private void directoryPickerBtn1_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog folderDialog = new FolderBrowserDialog();

        DialogResult folderResult = folderDialog.ShowDialog();
        if (folderResult == DialogResult.OK)
        {

            directoryTextbox1.Text = folderDialog.SelectedPath;
        }


    }

    private void directoryPickerBtn2_Click(object sender, EventArgs e)
    {
        FolderBrowserDialog folderDialog = new FolderBrowserDialog();

        DialogResult folderResult = folderDialog.ShowDialog();
        if (folderResult == DialogResult.OK)
        {
            directoryTextbox2.Text = folderDialog.SelectedPath;
        }
    }

    private void copyBtn_Click(object sender, EventArgs e)
    {
        string source = (directoryTextbox1.Text);
        string target = (directoryTextbox2.Text);



        DirectoryInfo dirSource = new DirectoryInfo(source);
        DirectoryInfo dirTarget = new DirectoryInfo(target);

        try
        {
            CopyAll(dirSource, dirTarget);

            if (logList.Count > 0)
            {
                using (StreamWriter sw = new StreamWriter(target + @"\log.txt", false))
                {
                    foreach (string error in logList)
                    {
                        sw.WriteLine(error);

                    }


                }
            }


            DialogResult result = MessageBox.Show("Copy Succeeded", "Success");
            if (result == DialogResult.OK)
            {
                string myPath = dirTarget.ToString();
                System.Diagnostics.Process prc = new System.Diagnostics.Process();
                prc.StartInfo.FileName = myPath;
                prc.Start();
            }
        }
        catch (Exception)
        {
            MessageBox.Show("Copy Failed", "Failed");
        }


    }
}

} }

From your code it seems that you never clear the logList, this means that it appears the file is being appending because the logList still contains all of the old entries. 从您的代码看来,您永远不会清除logList,这意味着它似乎正在添加文件,因为logList仍包含所有旧条目。

You'll need to clear the list between copies if you only want relevant entries to that copy, either before you start copying or after you finish writing the file. 如果只希望该副本的相关条目(在开始复制之前或完成写入文件之后),则需要清除副本之间的列表。

This would be better as a separate method 作为单独的方法,这会更好

    try
    {
        CopyAll(dirSource, dirTarget);

        SaveLog(target + @"\log.txt");

        ClearLog();
        //...
    }

    private void SaveLog(string filename)
    {
        if (logList.Count > 0)
        {
            FileStream fs = File.Open(target + @"\log.txt", FileMode.Create);
            using (StreamWriter sw = new StreamWriter(fs))
            {
                foreach (string error in logList)
                {
                    sw.WriteLine(error);
                }
            }
        }
    }

As @Reza Aghaei pointed out in comments , the problem is that you do not clear the logList . 正如@Reza Aghaei 在评论中指出的那样 ,问题在于您没有清除logList

The file gets created anew every time, but each time you click the Copy button, the loglist still contains the results of the previous copy action. 每次都会重新创建该文件,但是每次单击“复制”按钮时,日志列表仍包含上一个复制操作的结果。

So you need to clear the list when starting a new copy: 因此,在开始新副本时需要清除列表:

private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
    logList.Clear();

    // ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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