Laden...

Wie kann ich Code in Methoden auslagern und Variablen effizienter nutzen?

Erstellt von anideath vor 6 Jahren Letzter Beitrag vor 6 Jahren 5.705 Views
A
anideath Themenstarter:in
6 Beiträge seit 2017
vor 6 Jahren
Wie kann ich Code in Methoden auslagern und Variablen effizienter nutzen?

Moinsen,

ich bin noch blutiger Anfänger was C# und allgemein proggen angeht. Ich hab jetzt mein erstes Programm geschrieben, was genau das tut was ich gerne möchte aber der Code sieht in meinen Augen komisch aus und ständig brauchte ich die ganzen Variablen wieder. Ich habe mir alles selber beigebracht ohne Bücher sondern einfach nur durch die Dokumentation und Stackoverflow. Gibt es Möglichkeiten einigen Code in Methoden zu speichern ? Was kann man sonst noch so verbessern und was habe ich richtig bzw falsch gemacht in Bezug auf Ressourcen, Speed usw (auch wenn das prog eh nix verbraucht).

Naja hier ist der Code, würde mich freuen wenn man jemand drüber schaut 😃

using Microsoft.Win32;
using System;
using System.IO;
using System.Windows.Forms;


namespace OperaProfileLauncher
{
    public partial class OperaProfileLauncher : Form
    {
        public OperaProfileLauncher()
        {
            InitializeComponent();
            
            this.comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;

        }

        private void Form1_Load(object sender, EventArgs e)
        {

            string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string pdir = appdata + "" + "\\Opera Software\\Opera Stable\\Profile";
            string maindir = appdata + "" + "\\Opera Software\\Opera Stable";
            bool exists = System.IO.Directory.Exists(pdir);

            if (exists)
            {

                string[] files = Directory.GetFiles(pdir);
                string[] dirs = Directory.GetDirectories(pdir);

                foreach (string item2 in dirs)
                {
                    FileInfo f = new FileInfo(item2);

                    comboBox1.Items.Add(f.Name);

                }

                foreach (string item in files)
                {
                    FileInfo f = new FileInfo(item);

                    comboBox1.Items.Add(f.Name);

                }
            }

            else
            {
                System.IO.Directory.CreateDirectory(pdir);
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem == null)
            {
                MessageBox.Show("Nichts ausgewählt");
            }
            else
            {
                if (rbStable.Checked == true)
                {


                    System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
                    string InstallPathStable = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Opera Software", "Last Stable Install Path", null);
                    string test = InstallPathStable + @"launcher.exe";
                    pProcess.StartInfo.FileName = test;
                    var s1 = @"""";
                    var s2 = "/" + comboBox1.SelectedItem;
                    var cbox = comboBox1.SelectedItem;
                    string arg = "--user-data-dir=";
                    string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    string pdir = appdata + "" + "\\Opera Software\\Opera Stable\\Profile";




                    pProcess.StartInfo.Arguments = arg + "" + s1 + "" + pdir + "" + s2 + "" + s1;
                    pProcess.StartInfo.UseShellExecute = false;
                    pProcess.StartInfo.RedirectStandardOutput = true;
                    pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    pProcess.StartInfo.CreateNoWindow = true;
                    pProcess.Start();
                    string output = pProcess.StandardOutput.ReadToEnd();
                    pProcess.WaitForExit();
                }

                if (rbBeta.Checked == true)
                {

                    System.Diagnostics.Process pProcess = new System.Diagnostics.Process();

                    string InstallPathBeta = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Opera Software", "Last beta Install Path", null);

                    string test = InstallPathBeta + @"launcher.exe";
                    pProcess.StartInfo.FileName = test;
                    var s1 = @"""";
                    var s2 = "/" + comboBox1.SelectedItem;
                    var cbox = comboBox1.SelectedItem;
                    string arg = "--user-data-dir=";
                    string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

                    string pdirBeta = appdata + "" + "\\Opera Software\\Opera Next\\Profile\\";




                    pProcess.StartInfo.Arguments = arg + "" + s1 + "" + pdirBeta + "" + s2 + "" + s1;
                    pProcess.StartInfo.UseShellExecute = false;
                    pProcess.StartInfo.RedirectStandardOutput = true;
                    pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    pProcess.StartInfo.CreateNoWindow = true;
                    pProcess.Start();
                    string output = pProcess.StandardOutput.ReadToEnd();
                    pProcess.WaitForExit();
                }

                if (rbDev.Checked == true)
                {

                    System.Diagnostics.Process pProcess = new System.Diagnostics.Process();

                    string InstallPathDev = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Opera Software", "Last developer Install Path", null);
                    string test = InstallPathDev + @"launcher.exe";
                    pProcess.StartInfo.FileName = test;
                    var s1 = @"""";
                    var s2 = "/" + comboBox1.SelectedItem;
                    var cbox = comboBox1.SelectedItem;
                    string arg = "--user-data-dir=";
                    string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

                    string pdirDev = appdata + "" + "\\Opera Software\\Opera Developer\\Profile\\";



                    pProcess.StartInfo.Arguments = arg + "" + s1 + "" + pdirDev + "" + s2 + "" + s1;
                    pProcess.StartInfo.UseShellExecute = false;
                    pProcess.StartInfo.RedirectStandardOutput = true;
                    pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    pProcess.StartInfo.CreateNoWindow = true;
                    pProcess.Start();
                    string output = pProcess.StandardOutput.ReadToEnd();
                    pProcess.WaitForExit();
                }
            }

        }

        private void button2_Click(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            if (comboBox1.SelectedItem == null)
            {
                MessageBox.Show("Nichts");
            }
            else
            {
                if (rbStable.Checked == true)
                {
                    string folder = comboBox1.Text;
                    string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    string pathStable = appdata + "" + "\\Opera Software\\Opera Stable\\Profile\\" + folder;
                   

                    string newpathStable = appdata + "" + "\\Opera Software\\Opera Stable\\Backup\\" + folder;


                    string path = pathStable;
                    string[] dirs = Directory.GetDirectories(path, "*.*", SearchOption.AllDirectories);
                    string newpath = newpathStable;
                    try
                    {
                        Directory.CreateDirectory(newpath);
                    }
                    catch (IOException ex)
                    {
                        Console.WriteLine(ex.Message);
                    }

                    for (int j = 0; j < dirs.Length; j++)
                    {
                        try
                        {
                            Directory.CreateDirectory(dirs[j].Replace(path, newpath));
                        }
                        catch (IOException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
                    for (int j = 0; j < files.Length; j++)
                    {
                        try
                        {
                            File.Copy(files[j], files[j].Replace(path, newpath), true);
                           
                        }
                        catch (IOException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }

                if (rbBeta.Checked == true)
                {
                    string folder = comboBox1.Text;
                    string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    string pathBeta = appdata + "" + "\\Opera Software\\Opera Next\\Profile\\" + folder;
                    //     var s1 = @"""";

                    string newpathBeta = appdata + "" + "\\Opera Software\\Opera Next\\Backup\\" + folder;

                    string path = pathBeta;
                    string[] dirs = Directory.GetDirectories(path, "*.*", SearchOption.AllDirectories);
                    string newpath = newpathBeta;
                    try
                    {
                        Directory.CreateDirectory(newpath);
                    }
                    catch (IOException ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    for (int j = 0; j < dirs.Length; j++)
                    {
                        try
                        {
                            Directory.CreateDirectory(dirs[j].Replace(path, newpath));
                        }
                        catch (IOException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
                    for (int j = 0; j < files.Length; j++)
                    {
                        try
                        {
                            File.Copy(files[j], files[j].Replace(path, newpath), true);
                        
                        }
                        catch (IOException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }
                }

                if (rbDev.Checked == true)
                {
                    string folder = comboBox1.Text;
                    string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

                    string pathDeveloper = appdata + "" + "\\Opera Software\\Opera Developer\\Profile\\" + folder;
                    //    var s1 = @"""";


                    string newpathDeveloper = appdata + "" + "\\Opera Software\\Opera Developer\\Backup\\" + folder;

                    string path = pathDeveloper;
                    string[] dirs = Directory.GetDirectories(path, "*.*", SearchOption.AllDirectories);
                    string newpath = newpathDeveloper;
                    try
                    {
                        Directory.CreateDirectory(newpath);
                    }
                    catch (IOException ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                    for (int j = 0; j < dirs.Length; j++)
                    {
                        try
                        {
                            Directory.CreateDirectory(dirs[j].Replace(path, newpath));
                        }
                        catch (IOException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }
                    }

                    string[] files = Directory.GetFiles(path, "*.*", SearchOption.AllDirectories);
                    for (int j = 0; j < files.Length; j++)
                    {
                        try
                        {
                            File.Copy(files[j], files[j].Replace(path, newpath), true);

                        }
                        catch (IOException ex)
                        {
                            Console.WriteLine(ex.Message);
                        }

                    }
                }
            }
        }
            

                   

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {


        }
        
        private void button2_Click_1(object sender, EventArgs e)
        {



        }

        private void button2_Click_2(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(textBox1.Text))
            {
                MessageBox.Show("Bitte Namen angeben.");
            }
            else
            {
                if (rbStable.Checked == true)
                {
                    string folder = textBox1.Text;
                    string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    string pdir = appdata + "" + "\\Opera Software\\Opera Stable\\Profile\\";


                    string pdir2 = pdir + folder;



                    if (Directory.Exists(pdir2))
                    {
                        MessageBox.Show("Profil schon Vorhanden.");

                    }
                    else
                    {
                        comboBox1.Items.Add(textBox1.Text);
                        DirectoryInfo di = Directory.CreateDirectory(pdir2);
                        comboBox1.SelectedIndex = comboBox1.FindStringExact(textBox1.Text);

                   

                        if (comboBox1.Items.Contains(comboBox1.Items))
                        {

                            string[] files = Directory.GetFiles(pdir);
                            string[] dirs = Directory.GetDirectories(pdir);
                            foreach (string item2 in dirs)
                            {
                                FileInfo f = new FileInfo(item2);

                                comboBox1.Items.Add(f.Name);

                            }

                            foreach (string item in files)
                            {
                                FileInfo f = new FileInfo(item);

                                comboBox1.Items.Add(f.Name);

                            }
                        }
                    }
                }

                if (rbBeta.Checked == true)
                {
                    string folder = textBox1.Text;
                    string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    string pdirBeta = appdata + "" + "\\Opera Software\\Opera Next\\Profile\\";


                    string pdir2 = pdirBeta + folder;



                    if (Directory.Exists(pdir2))
                    {
                        MessageBox.Show("Profil schon Vorhanden.");

                    }
                    else
                    {
                        comboBox1.Items.Add(textBox1.Text);
                        DirectoryInfo di = Directory.CreateDirectory(pdir2);
                        comboBox1.SelectedIndex = comboBox1.FindStringExact(textBox1.Text);



                        if (comboBox1.Items.Contains(comboBox1.Items))
                        {

                            string[] files = Directory.GetFiles(pdirBeta);
                            string[] dirs = Directory.GetDirectories(pdirBeta);
                            foreach (string item2 in dirs)
                            {
                                FileInfo f = new FileInfo(item2);

                                comboBox1.Items.Add(f.Name);

                            }

                            foreach (string item in files)
                            {
                                FileInfo f = new FileInfo(item);

                                comboBox1.Items.Add(f.Name);

                            }
                        }
                    }
                }

                if (rbDev.Checked == true)
                {
                    string folder = textBox1.Text;
                    string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    string pdirDev = appdata + "" + "\\Opera Software\\Opera Developer\\Profile\\";

                    string pdir2 = pdirDev + folder;



                    if (Directory.Exists(pdir2))
                    {
                        MessageBox.Show("Profil schon Vorhanden.");

                    }
                    else
                    {
                        comboBox1.Items.Add(textBox1.Text);
                        DirectoryInfo di = Directory.CreateDirectory(pdir2);
                        comboBox1.SelectedIndex = comboBox1.FindStringExact(textBox1.Text);


                        if (comboBox1.Items.Contains(comboBox1.Items))
                        {

                            string[] files = Directory.GetFiles(pdirDev);
                            string[] dirs = Directory.GetDirectories(pdirDev);
                            foreach (string item2 in dirs)
                            {
                                FileInfo f = new FileInfo(item2);

                                comboBox1.Items.Add(f.Name);

                            }

                            foreach (string item in files)
                            {
                                FileInfo f = new FileInfo(item);

                                comboBox1.Items.Add(f.Name);

                            }
                        }
                    }
                }
            }

        }

        private void tArg_TextChanged(object sender, EventArgs e)
        {

        }

        private void button5_Click(object sender, EventArgs e)
        {
            MessageBox.Show("DU klickst button");
        }

        private void bDelete_Click(object sender, EventArgs e)
        {
       
            var s2 = comboBox1.SelectedItem;
            var cbox = comboBox1.SelectedItem;
         
            string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string pdir = appdata + "" + "\\Opera Software\\Opera Stable\\Profile\\";
            string pdirBeta = appdata + "" + "\\Opera Software\\Opera Next\\Profile\\";
            string pdirDev = appdata + "" + "\\Opera Software\\Opera Developer\\Profile\\";
            string folder = textBox1.Text;
            if (comboBox1.SelectedItem == null)
            {
                MessageBox.Show("Nichts ausgewählt");
            }
            else
            {
                if (rbStable.Checked == true)
                {
                    DialogResult result = MessageBox.Show("Willst du das Profil wirklich löschen ?",
                   "Caption", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (result == DialogResult.Yes)
                    {
                        try
                        {
                            comboBox1.Items.Remove(s2);
                            Directory.Delete(pdir + s2, true);

                       
                            MessageBox.Show("Profil Entfernt!");
                        }
                        catch { }
                    }

                }
                else { }

                if (rbBeta.Checked == true)
                {
                    DialogResult result = MessageBox.Show("Willst du das Profil wirklich löschen ?",
                   "Caption", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (result == DialogResult.Yes)
                    {
                        try
                        {
                            comboBox1.Items.Remove(s2);
                            Directory.Delete(pdirBeta + s2, true);

                            
                        
                        }
                        catch (Exception) { }
                    }
                }
                else { }

                if (rbDev.Checked == true)
                {
                    DialogResult result = MessageBox.Show("Willst du das Profil wirklich löschen ?",
                   "Caption", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

                    if (result == DialogResult.Yes)
                    {
                        try
                      {


                            comboBox1.Items.Remove(s2);
                            Directory.Delete(pdirDev + s2, true);
                        
                            MessageBox.Show("Profil Entfernt!");


                     }
                        catch (Exception) { }
                    }





                }
            }
        }

        private void rbStable_CheckedChanged(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string pdir = appdata + "" + "\\Opera Software\\Opera Stable\\Profile";
            bool exists = System.IO.Directory.Exists(pdir);

            if (exists)
            {

                string[] files = Directory.GetFiles(pdir);
                string[] dirs = Directory.GetDirectories(pdir);

                foreach (string item2 in dirs)
                {
                    FileInfo f = new FileInfo(item2);

                    comboBox1.Items.Add(f.Name);

                }

                foreach (string item in files)
                {
                    FileInfo f = new FileInfo(item);

                    comboBox1.Items.Add(f.Name);

                }
            }
        }

        private void rbBeta_CheckedChanged(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string pdir = appdata + "" + "\\Opera Software\\Opera Next\\Profile";
            bool exists = System.IO.Directory.Exists(pdir);

            if (exists)
            {

                string[] files = Directory.GetFiles(pdir);
                string[] dirs = Directory.GetDirectories(pdir);

                foreach (string item2 in dirs)
                {
                    FileInfo f = new FileInfo(item2);

                    comboBox1.Items.Add(f.Name);

                }

                foreach (string item in files)
                {
                    FileInfo f = new FileInfo(item);

                    comboBox1.Items.Add(f.Name);

                }
            }
        }

        private void rbDev_CheckedChanged(object sender, EventArgs e)
        {
            comboBox1.Items.Clear();
            string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            string pdir = appdata + "" + "\\Opera Software\\Opera Developer\\Profile";
            bool exists = System.IO.Directory.Exists(pdir);

            if (exists)
            {

                string[] files = Directory.GetFiles(pdir);
                string[] dirs = Directory.GetDirectories(pdir);

                foreach (string item2 in dirs)
                {
                    FileInfo f = new FileInfo(item2);

                    comboBox1.Items.Add(f.Name);

                }

                foreach (string item in files)
                {
                    FileInfo f = new FileInfo(item);

                    comboBox1.Items.Add(f.Name);

                }
            }

            else
            {
                System.IO.Directory.CreateDirectory(pdir);
            }

        }


    



        private void bMain_Click(object sender, EventArgs e)
        {

            if (rbStable.Checked == true)

            {

                System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
                string InstallPathStable = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Opera Software", "Last Stable Install Path", null);
          
                string test = InstallPathStable + @"launcher.exe";
                pProcess.StartInfo.FileName = test;
                var s1 = @"""";
                var s2 = "/";
                 string arg = "--user-data-dir=";
                string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string pdir = appdata + "" + "\\Opera Software\\Opera Stable\\";
        


                pProcess.StartInfo.Arguments = arg + "" + s1 + "" + pdir + "" + s2 + "" + s1;
                pProcess.StartInfo.UseShellExecute = false;
                pProcess.StartInfo.RedirectStandardOutput = true;
                pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                pProcess.StartInfo.CreateNoWindow = true;
                pProcess.Start();
                string output = pProcess.StandardOutput.ReadToEnd();
                pProcess.WaitForExit();

            }

            if(rbBeta.Checked == true)

            {

                System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
                string InstallPathBeta = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Opera Software", "Last beta Install Path", null);
                string test = InstallPathBeta + @"launcher.exe";
                pProcess.StartInfo.FileName = test;
                var s1 = @"""";
                var s2 = "/";
                string arg = "--user-data-dir=";
                string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string pdir = appdata + "" + "\\Opera Software\\Opera Next\\";



                pProcess.StartInfo.Arguments = arg + "" + s1 + "" + pdir + "" + s2 + "" + s1;
                pProcess.StartInfo.UseShellExecute = false;
                pProcess.StartInfo.RedirectStandardOutput = true;
                pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                pProcess.StartInfo.CreateNoWindow = true;
                pProcess.Start();
                string output = pProcess.StandardOutput.ReadToEnd();
                pProcess.WaitForExit();

            }

            if (rbDev.Checked == true)

            {

                System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
                string InstallPathDev = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Opera Software", "Last developer Install Path", null);
                string test = InstallPathDev + @"launcher.exe";
                pProcess.StartInfo.FileName = test;
                var s1 = @"""";
                var s2 = "/";
                string arg = "--user-data-dir=";
                string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                string pdir = appdata + "" + "\\Opera Software\\Opera Developer\\";



                pProcess.StartInfo.Arguments = arg + "" + s1 + "" + pdir + "" + s2 + "" + s1;
                pProcess.StartInfo.UseShellExecute = false;
                pProcess.StartInfo.RedirectStandardOutput = true;
                pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                pProcess.StartInfo.CreateNoWindow = true;
                pProcess.Start();
                string output = pProcess.StandardOutput.ReadToEnd();
                pProcess.WaitForExit();

            }

        }


    }
}

16.806 Beiträge seit 2008
vor 6 Jahren

a) bitte poste in Zukuft im richtigen Forenbereich
b) hab ich Deinen Pastebin Link gelöscht.

Wenn Du hier Code für den Review zeigen willst, dann poste ihn auch bitte direkt im Forum.
Siehe auch die Regeln dazu: Code-Review Regeln

A
anideath Themenstarter:in
6 Beiträge seit 2017
vor 6 Jahren

Sorry, hatte ein wenig vorschnell gehandelt und nicht richtig nachgeschaut. Habs geändert 😃

T
2.219 Beiträge seit 2008
vor 6 Jahren

@anideath
Nach einem kompletten durchscrollen, werde ich dir nur den Tipp geben aufzuräumen.
Du hast zu viel Redundanz, du den immer gleichen Code.
Du kannst locker 50-60% sparen, wenn du deinen Code mit einer Methode zum starten deines Process zusammen packst.
Hier würden 2-3 Parameter reichen und fertig.
Ich mache mir deshalb auch keine Mühe den Rest des Codes zu lesen.

T-Virus

Developer, Developer, Developer, Developer....

99 little bugs in the code, 99 little bugs. Take one down, patch it around, 117 little bugs in the code.

A
anideath Themenstarter:in
6 Beiträge seit 2017
vor 6 Jahren

@anideath
Nach einem kompletten durchscrollen, werde ich dir nur den Tipp geben aufzuräumen.
Du hast zu viel Redundanz, du den immer gleichen Code.
Du kannst locker 50-60% sparen, wenn du deinen Code mit einer Methode zum starten deines Process zusammen packst.
Hier würden 2-3 Parameter reichen und fertig.
Ich mache mir deshalb auch keine Mühe den Rest des Codes zu lesen.

T-Virus

Das hatte ich auch irgendwie vor in einer Methode zu speichern. Checke es aber noch nicht so ganz wie ich die dann im button_clicked event aufrufe. Das soll rein aber die Variable InstallPathStable ändert sich halt wenn andere radioboxen aktiviert sind.

                    System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
                    string InstallPathStable = (string)Registry.GetValue(@"HKEY_CURRENT_USER\Software\Opera Software", "Last Stable Install Path", null);
                    string test = InstallPathStable + @"launcher.exe";
                    pProcess.StartInfo.FileName = test;
                    var s1 = @"""";
                    var s2 = "/" + comboBox1.SelectedItem;
                    var cbox = comboBox1.SelectedItem;
                    string arg = "--user-data-dir=";
                    string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
                    string pdir = appdata + "" + "\\Opera Software\\Opera Stable\\Profile";




                    pProcess.StartInfo.Arguments = arg + "" + s1 + "" + pdir + "" + s2 + "" + s1;
                    pProcess.StartInfo.UseShellExecute = false;
                    pProcess.StartInfo.RedirectStandardOutput = true;
                    pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                    pProcess.StartInfo.CreateNoWindow = true;
                    pProcess.Start();
                    string output = pProcess.StandardOutput.ReadToEnd();
                    pProcess.WaitForExit();

Wüsste noch nicht wie ich das Umsetzen kann da ich noch nicht mit Methoden gearbeitet habe. Aber ich Probieren mal weiter. Eventuell kriege ich ja noch den ein oder anderen Tipp xD

4.931 Beiträge seit 2008
vor 6 Jahren

Hallo,

dann lies dir mal im OpenBook dazu das entsprechende Kapitel durch: 3.5 Methoden eines Objekts (bzw. "Methoden einer Klasse").

Wenn du Visual Studio hast, dann kannst du dort auch aus deinem Code eine Methode erzeugen lassen. Dazu einfach die passenden Codezeilen selektieren und dann mittels Kontextmenü "Methode extrahieren" aufrufen.

Den restlichen ähnlichen Code ersetzt du dann einfach durch den Methodenaufruf (und änderst die Parameter entsprechend).

16.806 Beiträge seit 2008
vor 6 Jahren

anideath, bitte beachte (endlich) die Forenregeln und vermeide Full Quotes
[Hinweis] Wie poste ich richtig?

3.003 Beiträge seit 2006
vor 6 Jahren

Ich nehm mal willkürlich ein paar Kritikpunkte heraus.

Zum einen ist diese exzessive Benutzung von Codebehind tödlich. Code-Behind dient - im besten Fall -
zur Steuerung von UI-Logik: wenn eine Taste in Textbox xy gedrückt wird, ändere deren Hintergrundfarbe auf rot. Solche oder ähnliche Sachen.
Du allerdings hast da fröhlich deine Anwendungslogik verteilt. Auch in WinForms sollte aber nach Möglichkeit ein Schichtenmodell verwendet werden: [Artikel] Drei-Schichten-Architektur

Das zieht gleich Kritikpunkt zwei nach sich. Lerne, was Databinding ist, und benutze es. Du sparst dir schätzungsweise 50% deines Spaghetticodes. Kein Mensch füllt Daten einer Oberfläche von Hand, wenn er seine geistige Gesundheit länger behalten möchte.

Soweit Kritik zur Struktur. Zu Inhalt und Form:

a) [Artikel] C#: Richtlinien für die Namensvergabe
b) du baust öfter mal eine Zeichenkette zusammen und führst dafür teilweise 3-4 temporäre Hilfsvariablen ein. Dabei benutzt du auch noch diese grässliche Angewohnheit aus der Java-Welt, Zeichenketten mit Hilfe von leeren Strings zu verketten. Vielleicht sehe nur ich das so, aber ich finde diese Notation schon mehr als hässlich.

Schau dir mal string.Format oder (ab Visual Studio 2017) Zeichenketteninterpolation an:

Du:


string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string pdir = appdata + "" + "\\Opera Software\\Opera Stable\\Profile";
bool exists = System.IO.Directory.Exists(pdir);

if (exists)

Die Variable maindir wird nie benutzt. (Übrigens: Namensvergabe. Wofür steht pDir? Clean Code, Leute.)

string.format:


var profileDir = string.Format(@"{0}\Opera Software\Opera Stable\Profile", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
if (Directory.Exists(profileDir))

string interpolation:


var profileDir = $@"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\Opera Software\Opera Stable\Profile";

if (Directory.Exists(profileDir))

Lass den Code reden. if(Directory.Exists(directoryName)) ist viel deutlicher als if(exists). Schieb nur in Fällen, wo es der Übersicht dient, Werte in zusätzliche Variable.

c) Deine catches machen IMMER ein Console.Write(). Wenn du Ausnahmen nicht behandeln möchtest, dann fang sie auch nicht. Und wieso Console.Write in einem WinForms-Program irgendwie nicht so sinnvoll ist, sollte auf der Hand liegen. Die einzige Stelle, wo du nicht Console.Write in einem catch machst, ist ein leerer catch, und der ist noch übler.

d) alle Code-Behind-Methoden geben dir einen Sender mit. Es ist eine Unart, die zu ignorieren und stattdessen auf benannten Controls zu arbeiten: immerhin kannst du das nur weil du als Programmierer in dem Moment weisst, dass dies die richtigen Controls sind. Andere Programmierer - auch du selbst, in der Zukunft - haben dieses Wissen nicht und laufen unnötig in Schwierigkeiten, deinen Code nachzuvollziehen.

e)


if (rbStable.Checked == true)

Nein. [Tipp] Anfängerhinweis == true / == false

Die Prozess-Starterei sieht auch seltsam aus - hab' ich mir jetzt aber nicht näher angeschaut, vielleicht möchte das jemand anderes tun.

Alles in allem für den ersten Versuch nicht so übel, wie mein Posting klingt. Dennoch stark verbesserungswürdig. Ich müsste mich sehr täuschen, wenn man dieselbe Funktion nicht mit <100 Zeilen Code hinkriegen könnte.

Grüße,

LaTino

"Furlow, is it always about money?"
"Is there anything else? I mean, how much sex can you have?"
"Don't know. I haven't maxed out yet."
(Furlow & Crichton, Farscape)

1.029 Beiträge seit 2010
vor 6 Jahren

Hi,

möchte mir auch ein paar Hinweise erlauben.

  1. Pfade baut man mit Path.Combine zusammen
  2. Du verwendest nirgends irgendwelche code-doku (in wenigen wochen musst du schon selbst jede Methode komplett lesen um zu wissen was diese überhaupt macht)
  3. Deine Controls tragen zusätzlich zur fehlenden doku oft noch ihren Standard-namen
  4. Wenn du eine einzige Variable hättest, in der jeweils der aktuelle Pfad stehst fällt unglaublich viel Code bei dir einfach weg (unter anderem kannst du alle Methoden die Prozesse starten, sowie alle Methoden die die Daten in die Combobox packen jeweils auf eine reduzieren
  5. Für Directories sollte man konsequenterweise auch die Klasse DirectoryInfo und nicht FileInfo nutzen

LG

F
10.010 Beiträge seit 2004
vor 6 Jahren

Ich habe mir alles selber beigebracht ohne Bücher sondern einfach nur durch die Dokumentation und Stackoverflow.

Vollkommen falsche Herangehensweise.
Glaubst du tatsächlich das etwas so komplexes wie die Softwareentwicklung ohne Grundlagen zu meistern ist?

P
63 Beiträge seit 2016
vor 6 Jahren

@anideath
solltest Du das hier noch Lesen und das Programmieren nicht aufgegeben haben dann Kaufe dir diese Buch "Visual C# 2015 – Grundlagen, Profiwissen und Rezepte".
Ich habe unheimlich viel dadurch gelernt. Wenn man dann noch 1-2 Jahre an Erfahrung Sammelt kommt so langsam brauchbar Code zusammen 😉