c#中读取修改txt文件内容后,没有保存的方法吗?
3个回答
展开全部
FileStream fs = new FileStream("路径",FileMode.Open,FileAccess.Read);
StreamReader sr = new StreamReader(fs,Encoding.GetEncoding("GB2312"));
string str = sr.ReadLine();
for(int i=0; str != null;i++)
{
str = str.Replace(".","</br>");//根据"."字符,判断是否换行
Response.Write(str);
str = sr.ReadLine();
}
sr.Close();
fs.Close();
1)创建txt文件【web.config】
--------------------------------------------------------------------
<appSettings>
<add key="EditChars" value="D:\Site\ZJPS\TextFile\EditChars.txt"/>
</appSettings>
2) 页面的CS文件中:
--------------------------------------------------------------------
【1】 获取txt文件位置: protected string FileName = System.Configuration.ConfigurationManager.AppSettings["EditChars"].ToString();
【2】 文件操作:创建、写、读 文件。
#region 文件操作
/// <summary>
/// 创建txt文件
/// </summary>
public void CreateToFile()
{
StreamWriter SW;
SW = File.CreateText(FileName);
SW.Close();
}
/// <summary>
/// 写文件
/// </summary>
public void WriteToFile()
{
string InsertStr = "";
if (!File.Exists(FileName))
{
CreateToFile();
InsertStr = "Content#DateTime#!"; //txt文件中用它来表示字段
}
InsertStr += this.txtContent.Text.ToString() + "#";
InsertStr += Convert.ToString(Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd")) + "#";
File.AppendAllText(FileName, InsertStr + "!", Encoding.BigEndianUnicode);
}
/// <summary>
/// 读取文件
/// </summary>
/// <returns></returns>
public string ReadTextFileDate()
{
string strInput = "";
string GetStream = ""; if (File.Exists(FileName))
{
StreamReader sr = new StreamReader(FileName, UnicodeEncoding.GetEncoding("gb2312"));
strInput = sr.ReadLine();
while (strInput != null)
{
GetStream += strInput;
strInput = sr.ReadLine();
}
sr.Close();
}
else
{
lblContents.Text = "myFile.txt does not exist!";
}
return GetStream;
}
#endregion/// <summary> /// 修改txt中的内容/// </summary>public void UpdateTextFile(string FileName, string StrCount) { System.IO.StreamReader sr = new System.IO.StreamReader(FileName); string s = sr.ReadToEnd(); sr.Close(); s = s.Replace(s, StrCount); System.IO.StreamWriter sw = new System.IO.StreamWriter(FileName, false); sw.Write(s); sw.Close(); } 【3】 构建表
public DataTable EditCharsBound()
{
ReadTextFileDate();
DataTable dt = new DataTable();
dt.Columns.Add("Content", System.Type.GetType("System.String")); //新表的列字段
dt.Columns.Add("DateTime", System.Type.GetType("System.String")); //Content#DateTime#!
if (ViewState["EditChars"].ToString() != "")
{
string[] EditChars = new string[2000];
EditChars = ViewState["EditChars"].ToString().Split('!');
for (int i = 1; i < EditChars.Length - 1; i++)
{
string StrSomeInfo = EditChars[i].ToString();
DataRow NewRow = dt.NewRow();
string[] StrData = StrSomeInfo.ToString().Split('#');
NewRow["Content"] = StrData[0].ToString();
NewRow["DateTime"] = StrData[1].ToString();
dt.Rows.Add(NewRow);
}
}
return dt;
}3) 有了DataTable然后对txt数据进行条件查询
--------------------------------------------------------------------
【1】直接DataTable.Select()进行查询,得到DataRow[]
public DataRow[] GetByIDValue()
{
string QueryStr = "";
DataTable table1 =EditCharsBound();
if (Request.QueryString["id"] == null)
QueryStr = "ID=1";
else
QueryStr = "ID=" + Request.QueryString["id"].ToString();
//用DataTable.Select来进行数据查询,如:table1.Select("Content='测试'","DateTime DESC");
//DataTable.Select(参数根据情况而定)
DataRow[] rows = table1.Select(QueryStr);
return rows;
}
--------------------------------------------------------------------
【2】若要把DataRow[]再构建成表时,代码如下:
public DataTable GetSelectValue()
{
DataTable NewTable = new DataTable();
NewTable.Columns.Add("Content", System.Type.GetType("System.String")); //新表的列字段r
NewTable.Columns.Add("DateTime", System.Type.GetType("System.String")); DataTable table1 = EditCharsBound();
DataRow[] rows = table1.Select("Content='测试'","DateTime DESC");
if (rows.Length > 0)
{
for (int i = 0; i < rows.Length; i++)
{
DataRow dtr = NewTable.NewRow();
dtr["Content"] = rows[i]["Content"].ToString();
dtr["DateTime"] = rows[i]["DateTime"].ToString();
NewTable.Rows.Add(dtr);
}
}
return NewTable;
}若是用只读方式读取TXT文件,如下:
/// <summary>
/// 按只读方式来读取txt文件
/// </summary>
public void ReadTextFileDate()
{
string strInput = "";
string GetStream = "";
if (File.Exists(FileName))
{
Stream fs = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
TextReader sr = new StreamReader(fs, UnicodeEncoding.GetEncoding("gb2312"));
strInput = sr.ReadLine();
while (strInput != null)
{
GetStream += strInput;
strInput = sr.ReadLine();
}
sr.Close();
fs.Close();
}
else
{
GetStream = "";
}
ViewState["GetStream"] = GetStream.ToString();
}
StreamReader sr = new StreamReader(fs,Encoding.GetEncoding("GB2312"));
string str = sr.ReadLine();
for(int i=0; str != null;i++)
{
str = str.Replace(".","</br>");//根据"."字符,判断是否换行
Response.Write(str);
str = sr.ReadLine();
}
sr.Close();
fs.Close();
1)创建txt文件【web.config】
--------------------------------------------------------------------
<appSettings>
<add key="EditChars" value="D:\Site\ZJPS\TextFile\EditChars.txt"/>
</appSettings>
2) 页面的CS文件中:
--------------------------------------------------------------------
【1】 获取txt文件位置: protected string FileName = System.Configuration.ConfigurationManager.AppSettings["EditChars"].ToString();
【2】 文件操作:创建、写、读 文件。
#region 文件操作
/// <summary>
/// 创建txt文件
/// </summary>
public void CreateToFile()
{
StreamWriter SW;
SW = File.CreateText(FileName);
SW.Close();
}
/// <summary>
/// 写文件
/// </summary>
public void WriteToFile()
{
string InsertStr = "";
if (!File.Exists(FileName))
{
CreateToFile();
InsertStr = "Content#DateTime#!"; //txt文件中用它来表示字段
}
InsertStr += this.txtContent.Text.ToString() + "#";
InsertStr += Convert.ToString(Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd")) + "#";
File.AppendAllText(FileName, InsertStr + "!", Encoding.BigEndianUnicode);
}
/// <summary>
/// 读取文件
/// </summary>
/// <returns></returns>
public string ReadTextFileDate()
{
string strInput = "";
string GetStream = ""; if (File.Exists(FileName))
{
StreamReader sr = new StreamReader(FileName, UnicodeEncoding.GetEncoding("gb2312"));
strInput = sr.ReadLine();
while (strInput != null)
{
GetStream += strInput;
strInput = sr.ReadLine();
}
sr.Close();
}
else
{
lblContents.Text = "myFile.txt does not exist!";
}
return GetStream;
}
#endregion/// <summary> /// 修改txt中的内容/// </summary>public void UpdateTextFile(string FileName, string StrCount) { System.IO.StreamReader sr = new System.IO.StreamReader(FileName); string s = sr.ReadToEnd(); sr.Close(); s = s.Replace(s, StrCount); System.IO.StreamWriter sw = new System.IO.StreamWriter(FileName, false); sw.Write(s); sw.Close(); } 【3】 构建表
public DataTable EditCharsBound()
{
ReadTextFileDate();
DataTable dt = new DataTable();
dt.Columns.Add("Content", System.Type.GetType("System.String")); //新表的列字段
dt.Columns.Add("DateTime", System.Type.GetType("System.String")); //Content#DateTime#!
if (ViewState["EditChars"].ToString() != "")
{
string[] EditChars = new string[2000];
EditChars = ViewState["EditChars"].ToString().Split('!');
for (int i = 1; i < EditChars.Length - 1; i++)
{
string StrSomeInfo = EditChars[i].ToString();
DataRow NewRow = dt.NewRow();
string[] StrData = StrSomeInfo.ToString().Split('#');
NewRow["Content"] = StrData[0].ToString();
NewRow["DateTime"] = StrData[1].ToString();
dt.Rows.Add(NewRow);
}
}
return dt;
}3) 有了DataTable然后对txt数据进行条件查询
--------------------------------------------------------------------
【1】直接DataTable.Select()进行查询,得到DataRow[]
public DataRow[] GetByIDValue()
{
string QueryStr = "";
DataTable table1 =EditCharsBound();
if (Request.QueryString["id"] == null)
QueryStr = "ID=1";
else
QueryStr = "ID=" + Request.QueryString["id"].ToString();
//用DataTable.Select来进行数据查询,如:table1.Select("Content='测试'","DateTime DESC");
//DataTable.Select(参数根据情况而定)
DataRow[] rows = table1.Select(QueryStr);
return rows;
}
--------------------------------------------------------------------
【2】若要把DataRow[]再构建成表时,代码如下:
public DataTable GetSelectValue()
{
DataTable NewTable = new DataTable();
NewTable.Columns.Add("Content", System.Type.GetType("System.String")); //新表的列字段r
NewTable.Columns.Add("DateTime", System.Type.GetType("System.String")); DataTable table1 = EditCharsBound();
DataRow[] rows = table1.Select("Content='测试'","DateTime DESC");
if (rows.Length > 0)
{
for (int i = 0; i < rows.Length; i++)
{
DataRow dtr = NewTable.NewRow();
dtr["Content"] = rows[i]["Content"].ToString();
dtr["DateTime"] = rows[i]["DateTime"].ToString();
NewTable.Rows.Add(dtr);
}
}
return NewTable;
}若是用只读方式读取TXT文件,如下:
/// <summary>
/// 按只读方式来读取txt文件
/// </summary>
public void ReadTextFileDate()
{
string strInput = "";
string GetStream = "";
if (File.Exists(FileName))
{
Stream fs = File.Open(FileName, FileMode.Open, FileAccess.Read, FileShare.Read);
TextReader sr = new StreamReader(fs, UnicodeEncoding.GetEncoding("gb2312"));
strInput = sr.ReadLine();
while (strInput != null)
{
GetStream += strInput;
strInput = sr.ReadLine();
}
sr.Close();
fs.Close();
}
else
{
GetStream = "";
}
ViewState["GetStream"] = GetStream.ToString();
}
更多追问追答
追问
先谢谢你给我提供了这么有意义的demo,我现在的问题是:已经存在的txt文件,修改之后再保存。例:test.txt,文件内容:abcde,然后读取test.txt,用replace()方法将a替换成b,即bbced保存在test.txt文件中,请问有没有类似save()的方法?
追答
不需要保存,不像我们人手动操作需要点保存,电脑操作,写进去了就进去了。
展开全部
Demo:
using (FileStream fs = new FileStream(fileName,
FileMode.OpenOrCreate, FileAccess.Write))
{
StreamWriter writer = new StreamWriter(fs,
Encoding.Default);
//将文本框的内容写入到文件流
writer.Write(richTextBox1.Text);
writer.Flush(); //刷新缓冲区
MessageBox.Show("文件保存成功!");
}
创建一个文件流中using中,确保文件操作完毕自动关闭
参数(文件名,打开方式,读取方式)
1.在文件流中创建一个文件写入类的对象,StreamWriter
2.之后以字符串形式将richTextBox中的内容写入到文件中
3.writer.Fluch() --> 确保缓冲区中的数据流被写入基础流中
(第一次回答,献丑了)
using (FileStream fs = new FileStream(fileName,
FileMode.OpenOrCreate, FileAccess.Write))
{
StreamWriter writer = new StreamWriter(fs,
Encoding.Default);
//将文本框的内容写入到文件流
writer.Write(richTextBox1.Text);
writer.Flush(); //刷新缓冲区
MessageBox.Show("文件保存成功!");
}
创建一个文件流中using中,确保文件操作完毕自动关闭
参数(文件名,打开方式,读取方式)
1.在文件流中创建一个文件写入类的对象,StreamWriter
2.之后以字符串形式将richTextBox中的内容写入到文件中
3.writer.Fluch() --> 确保缓冲区中的数据流被写入基础流中
(第一次回答,献丑了)
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
创建一个StreamWriter 对象,通过StreamWriter.WriteLine(“要保存的string”)
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询