Код не выполняется правильно в приложении Windows Forms - PullRequest
0 голосов
/ 21 января 2019

Я пытаюсь создать приложение для формы Windows, чтобы сделать то же самое, что и консольное приложение.Дизайн представляет собой просто окно с двумя метками (в дальнейшем я попытаюсь добавить индикатор выполнения), но по какой-то причине код работает неправильно.

            using System;
            using System.Collections.Generic;
            using System.IO;
            using System.Linq;
            using System.Reflection;
            using System.Text;
            using System.Threading;
            using System.Threading.Tasks;
            using System.Diagnostics;
            using System.ComponentModel;
            using System.Data;
            using System.Drawing;
            using System.Windows.Forms;

            namespace WindowsFormsApp1
            {
                public partial class Form1 : Form
                {
                    public Form1()
                    {
                        InitializeComponent();
                    }

                    private void label1_Click(object sender, EventArgs e)
                    {

                    }

                    private void Form1_Load(object sender, EventArgs e)
                    {
                        string date = DateTime.Now.ToString("ddMMyy");
                        string Source = @"G:\Personal\A1";
                        string Destination = @"D:\_Lil USB Backup\" + "b";
                        if (System.IO.Directory.Exists(Source))
                        {
                            if (System.IO.Directory.Exists(Destination))
                            {
                                infoBox.Text = "Backup already exists for today. U rem";
                            }
                            else
                            {
                                System.IO.Directory.CreateDirectory(Destination);
                            }
                            try
                            {
                                CopyAllFiles(Source, Destination);
                                infoBox.Text = "Files backed up successfully.";
                                if (System.IO.Directory.Exists(@"D:\" + date + @"System Volume Information"))
                                {
                                    Directory.Delete(@"D:\" + date + @"System Volume Information", true);
                                    infoBox.Text = "Files backed up successfully.\n System Volume Information folder deleted.\n Backup successfull.";
                                }
                                else
                                {
                                    infoBox.Text = "System Volume Information folder does not exist and therefore was not deleted.\n Backup successfull.";
                                }
                            }
                            catch (Exception ez)
                            {
                                infoBox.Text = "Umm, something didn't work. Oh maybe it was this? " + ez.Message;
                            }
                        }
                        else
                        {
                            infoBox.Text = "Source does not exist, try plugging the USB in dipshit.";
                        }
                    }

                    private static void CopyAllFiles(string Source, string Destination)
                    {
                        try
                        {
                            // Get the subdirectories for the specified directory.
                            DirectoryInfo dir = new DirectoryInfo(Source);
                            DirectoryInfo[] dirs = dir.GetDirectories();
                            if (!dir.Exists)
                            {
                                Label infoBoxErr = new Label();
                                infoBoxErr.Text = "Directory could not be found.";
                            }
                            // If the destination directory doesn't exist, create it.
                            if (!Directory.Exists(Destination))
                            {
                                Directory.CreateDirectory(Destination);
                            }
                            // Get the files in the directory and copy them to the new location.
                            FileInfo[] files = dir.GetFiles();
                            foreach (FileInfo file in files)
                            {
                                string temppath = Path.Combine(Destination, file.Name);
                                file.CopyTo(temppath, true);
                            }
                            foreach (DirectoryInfo subdir in dirs)
                            {
                                string temppath = Path.Combine(Destination, subdir.Name);
                                CopyAllFiles(subdir.FullName, temppath);
                            }
                        }
                        catch (Exception ex)
                        {
                            Label infoBoxErr = new Label();
                            infoBoxErr.Text = "Oh. Something didn't work, sorry. Might have been this: " + ex.Message + " lol!";
                        }
                    }

                    private void progressBar1_Click(object sender, EventArgs e)
                    {

                    }
                }
            }

Проблема заключается в том, что он выводит текст вярлыки, как и ожидалось, как будто это было успешно.Тем не менее, он не создает новую папку и не копирует какие-либо файлы.Я понятия не имею, почему, и это не дает мне никаких ошибок!

1 Ответ

0 голосов
/ 21 января 2019

Прежде всего вы ловите исключение в методе CopyAllFiles . И его код

    catch (Exception ex)
    {
        Label infoBoxErr = new Label();
        infoBoxErr.Text = "Oh. Something didn't work, sorry. Might have been this: " + ex.Message + " lol!";
    }

ничего не делает, потому что создает метку infoBoxErr в памяти и не отображает ее вообще.

Итак, следующий код

    try
    {
        CopyAllFiles(Source, Destination);
        infoBox.Text = "Files backed up successfully.";
        if (System.IO.Directory.Exists(@"D:\" + date + @"System Volume Information")) 
        {
            Directory.Delete(@"D:\" + date + @"System Volume Information", true);
            infoBox.Text = "Files backed up successfully.\n System Volume Information folder deleted.\n Backup successfull.";
    }
        else
        {  
            infoBox.Text = "System Volume Information folder does not exist and therefore was not deleted.\n Backup successfull.";
        }
    }
    catch (Exception ez)
    {
        infoBox.Text = "Umm, something didn't work. Oh maybe it was this? " + ez.Message;
    }

никогда не достигает блока catch (из-за внутренней перехвата в методе CopyAllFiles ) и просто отображает текст успеха.

Так что я бы посоветовал вам удалить эту внутреннюю защелку и посмотреть, что произойдет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...