C#读写文件

来源:百度知道 编辑:UC知道 时间:2024/09/27 15:41:28
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace _008518
{
public partial class frmEdit : Form
{
public frmEdit()
{
InitializeComponent();
}

private void btnSave_Click(object sender, EventArgs e)
{
FileStream fs;
try
{
fs = File.Create(txtFileName.Text);
}
catch
{
MessageBox.Show("建立文件时出错. " , "错误" , MessageBoxButtons.OK , MessageBoxIcon.Warning);
return;
}
byte[] content = new UTF8Encoding(true).GetBytes(lstContent.Text);
try
{

在每行后面加上"\n\r"就好了。
————————————————
如果楼主想保存的是在lstContent中选定项的文本的话,这个程序是没有错的,楼主可以在点击按钮前先选中其中一项,再保存。
但如果楼主是想保存lstContent中所有的文本的话,这样肯定是不行的。
需要把byte[] content = new UTF8Encoding(true).GetBytes(lstContent.Text);
改成:
string lstContenText = "";
for (int i = 0; i < lstContent.Items.Count; i++)
{

lstContenText += lstContent.Items[i].ToString() + "\n\r";
}
byte[] content = new UTF8Encoding(true).GetBytes(lstContenText);

我将你的程序编译了一下试了试,我因为不知道lstContent是什么控件,所以我将他换成了固定的文字列“ABCD”,程序可以正常运行。里面的文字也可以正常显示出来,所以你的问题应该是出在lstContent控件上,你再看看吧