所以对于我在c#中的第一个程序,我想制作一个机器人。 我已经制作了一些GUI,但一切都没有按照我想要的方式定位。
每当我尝试使用OpenFileDialog加载文件中没有特定内容的文本文件时,它会在富文本框中显示目录,而不是文件的实际内容。
加载文件时,我得到的不是实际内容:http://puu.sh/5kLL2.png
该文件的实际内容为“wepufhwoighwiar” 加载代码代码按钮:
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = @"C:\";
openFileDialog1.Title = "Browse Text Files";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.DefaultExt = "txt";
openFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
openFileDialog1.ReadOnlyChecked = true;
openFileDialog1.ShowReadOnly = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
proxieslist.Text = openFileDialog1.FileName;
}
}
答案 0 :(得分:4)
OpenFileDialog
无法为您打开该文件。它只是帮助您选择要打开的文件。要打开文件,您必须使用命名空间System.IO
中的某些类。这是一个简单的代码来读取所有文本(明文):
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
proxieslist.Text = System.IO.File.ReadAllText(openFileDialog1.FileName);
}
答案 1 :(得分:3)
只是为了添加一个有用的提示,最好像这样初始化你的对象,它减少了一些代码,看起来更漂亮,并减少了重复键入......:)
var openFileDialog1 =
new OpenFileDialog
{
InitialDirectory = @"C:\" ,
Title = "Browse Text Files" ,
CheckFileExists = true ,
CheckPathExists = true ,
DefaultExt = "txt" ,
Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*" ,
FilterIndex = 2 ,
RestoreDirectory = true ,
ReadOnlyChecked = true ,
ShowReadOnly = true
};
答案 2 :(得分:0)
作为另一种选择,您可以使用StreamReader
:
StreamReader sr = new StreamReader("C:\\cake.txt", Encoding.UTF8); //declare;
string cakeCode = sr.ReadToEnd(); //read cake.txt through to cakeCode (a string containing the text of cake's)
sr.Close(); //The End.