简体   繁体   中英

WPF C# Read a txt file in Textbox who is selected in combobox

Maybe this is an old question, but I can´t find a solution fpr my project. Let me explain:

  • I have 3 Textboxes, who I can fill with values.
  • 1 Button who save the values of the textboxes in a *.txt file. The Name of the file is the value of the first textboxes.
  • Then there is a ComboBox where I can select the txt files.
  • But I cant find the right code, when I selected a file, I want to see the 3 values(3 different lines) of the file into the Textboxes. Can someone help me, I will show you the Codes maybe its easier to understand.

the first code to save the values (tb1-3 = Textbox) in the txt file:

private void savebutton_click(object sender, RoutedEventArgs e)
{
    string folder = @"C:\Users\...\...\...\Debug\";
    string filename = tb1.Text + ", " + tb2.Text;
    string writerfile = folder + filename;
    using (StreamWriter writer = new StreamWriter(writerfile))
    {
        writer.WriteLine(this.tb1.Text);
        writer.WriteLine(this.tb2.Text);
        writer.WriteLine(this.tb3.Text);
    }
}

The second code is to show the txt files in the combobox(combo1):

private void comboboxloaded(object sender, RoutedEventArgs e)
{
    DirectoryInfo dinfo = new DirectoryInfo(@"C:\Users\...\...\...\Debug");
    FileInfo[] Files = dinfo.GetFiles("*.txt");
    foreach (FileInfo file in Files)
    {
        combo1.Items.Add(file);
    }
}

And know... I need help...

private void comboboxvalueselect(object sender, SelectionChangedEventArgs e)        
{
   // Maybe?????
   string fileName = combo1.SelectedItem.ToString();
   string filePath = System.IO.Path.Combine(@"C:\Users\...\...\...\Debug" + fileName + "*.txt");

   // and something with StreamReader??????
}

If I understand the question it could be as simple as using File.ReadAllLines

Opens a text file, reads all lines of the file into a string array, and then closes the file.

private void comboboxvalueselect(object sender, SelectionChangedEventArgs e)
{
   const string somePath = @"C:\Users\...\...\...\Debug";

   var fileName = combo1.SelectedItem.ToString();

   var filePath = Path.Combine(somePath , fileName);

   // where you need those lines to go
   someTextBox.Text = File.ReadAllLines(filePath);
}

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