我正在创建一个.net GUI,它将根据文本文件中的内容更改颜色。我无法弄清楚如何使用StreamWriter来创建文本文件,更具体地说,代码应该去哪里。这是我第一次尝试使用VS和C#,所以我有点迷失。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void textBox2_Copy14_TextChanged(object sender, TextChangedEventArgs e)
{
}
private void button2_Copy5_Click(object sender, RoutedEventArgs e)
{
}
private void CC_Futs_Click(object sender, RoutedEventArgs e)
{
}
private void FCOJ_Futs_Click(object sender, RoutedEventArgs e)
{
}
}
}
在此代码中,我将使用StreamWriter创建文本文件,您是否可以提供可能使用的代码示例?您可以在此时忽略按钮的单击事件,只是尝试了解此处的整体结构。
答案 0 :(得分:0)
要在Windows窗体应用程序启动时读取或写入文本文件,您需要使用窗体加载事件。加载事件在表单显示之前发生。这个例子足以让你前进。
private void Form1_Load(object sender, EventArgs e)
{
//Write to a file
StreamWriter sw = new StreamWriter(Application.StartupPath + @"\file.txt");
sw.WriteLine("some text here");
sw.Close();
sw.Dispose();
//read from a file
StreamReader sr = new StreamReader(Application.StartupPath + @"\file.txt");
String line = null;
while ((line = sr.ReadLine()) != null)
{
MessageBox.Show(line);
}
sr.Close();
sr.Dispose();
}