浏览文件并打开
##工程创建

创建一个c#的windows项目工程
在窗体上添加几个按键

在按键 --> 打开文件的 点击事件函数中添加代码
private void OpenFile_Click(object sender, EventArgs e) // 输入文本清空
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = true;//该值确定是否可以选择多个文件
dialog.Title = "请选择文件夹";
dialog.Filter = "所有文件(*.*)|*.*";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string file = dialog.FileName;
}
string path = dialog.FileName;
if (path == "")
{
return;
}
InputBox.Text = path;
using (System.IO.FileStream FileOpenAndRead = new System.IO.FileStream(path, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Read))
{
long FileLength = 0;
//跳过第一行4个字节和回车换行,一共6字节。
FileLength = FileOpenAndRead.Seek(0, System.IO.SeekOrigin.End); // 0到结束 返回长度
FileOpenAndRead.Seek(0, System.IO.SeekOrigin.Begin); //返回文件开头
byte[] buffer = new byte[FileLength];
int r = FileOpenAndRead.Read(buffer, 0, buffer.Length);
string str = System.Text.Encoding.UTF8.GetString(buffer);
InputBox.Text = str;
}
}
例图

按操作就能出现这样的画面了
在System.IO里还有许多其他类 功能大同小异 但是又是不同的东西 如果对于文件数据流处理比较复杂的话 还是混合其他的类 各种流包组装来用

#文件数据流的保存成文件
有打开就有保存功能 有OpenFileDialog 就有SaveFileDialog
同样 添加代码
private void CreatFile_Click(object sender, EventArgs e) // 输入文本清空
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "";
sfd.InitialDirectory = @"C:\";
sfd.Filter = "文本文件| *.txt";
sfd.ShowDialog();
string path = sfd.FileName;
if (path == "")
{
return;
}
System.IO.File.WriteAllText(path, str_out);//不同的平台 对于回车键的识别不同 vs文本框 出来的是 \n 电脑windows识别 \r\n 调试转换
MessageBox.Show("保存成功");
}
我这里就用了一个简单一点的函数 其他的操作暂时没用到 没必要ob了

over
本文介绍了如何在C#的Visual Studio 2019环境下,通过创建Windows项目工程,并利用OpenFileDialog和SaveFileDialog控件,实现以浏览方式打开和保存TXT文件。在OpenFileDialog中点击按钮可以弹出选择文件对话框,而使用SaveFileDialog则可实现文件的保存。此外,文章提到System.IO命名空间中包含多种类,可用于更复杂的文件数据流处理。
1万+

被折叠的 条评论
为什么被折叠?



