C#中怎么获取文件中的文字

CYGGYF 2012-02-20 09:21:55
我是初学者, 急急急!!! 想通过OpenFileDialog控件选择一个.txt文件或者word文档,把.txt或word文档文件中的字符以字符串的形式存到list<>集合中, 望能用实例帮忙解决一下, 谢谢!!!
...全文
35 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
threenewbee 2012-02-20
  • 打赏
  • 举报
回复
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.IO;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamReader sr = new StreamReader(ofd.FileName))
{
string s = sr.ReadToEnd();
List<string> lines = s.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).ToList();
... //放入你的代码
}
}
}
}
}
??????8 2012-02-20
  • 打赏
  • 举报
回复
if (!File.Exists("D:\\mytext.text"))
{
MessageBox.Show("目录不存在");
}
else
{
StreamReader sr = File.OpenText("D:\\mytext.text");
textBox2.Text=sr.ReadToEnd();
sr.Close();
sr.Dispose();

}

将上面的路径改为你openfiledialog读取的路径就OK了,放入list<>中要看你list是什么型的了

110,533

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧