简体   繁体   中英

How do I read the text of a resource txt file and put it into a TextBox in C# .net 4.0 WPF?

How do I read the text of a resource txt file and put it into a TextBox in C# .net 4.0 WPF? I have a TextBox in my form and a TXT file in my resources folder, how do I put the text from the TXT file (including the line breaks, double spaces, etc) into the TextBox?

Please simplify the code for me because I'm a beginner in C#... Thanks!

No need to provide code, there is already a very simple WPF Example for this exact problem, found here .

And btw, don't ask on SO for "Hey could you guys solve that for me!" you should ask questions more like "Hey i tried this, and that. Why didn't this work, what is wrong with that. I also read somewhere that this is considered bad, why exactly?". Show that you put work already into the problem, this will greatly increase the amount of time and effort people are willingly to put into your problem.

No difference reading file in WinForms or in WPF. Simply add to you window TextBox and load file via System.IO.File class.

Example :

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="auto"/>
    </Grid.RowDefinitions>
    <TextBox x:Name="tb" Margin="4"/>
    <Button Grid.Row="1" Content="Load file" x:Name="btnLoad" Click="btnLoad_Click" Width="60" HorizontalAlignment="Left" Margin="4"/>

</Grid>

and code behavior :

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void btnLoad_Click(object sender, RoutedEventArgs e)
    {
        tb.Text = File.ReadAllText(@"*path to file*");
    }
}

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