/// <summary> /// 写数据到文件 /// </summary> /// <param name="strDataList">行数据列表</param> /// <param name="filename">文件名</param> /// <returns>是否成功</returns> public static bool WriteToFile(List<string> strDataList,string filename) { try { //Pass the filepath and filename to the StreamWriter Constructor // StreamWriter sw = new StreamWriter(filename); StreamWriter sw = new StreamWriter(filename,false,Encoding.GetEncoding("gb2312")); sw.Write("", false); //Write a line of text foreach (string item in strDataList) { sw.WriteLine(item, true); } //Close the file sw.Close(); return true; } catch (Exception e) { return false; } } /// <summary> /// 从文件获取数据 /// </summary> /// <param name="fileName">文件名</param> /// <returns>行数据列表</returns> public static List<string> ReadFromFile(string fileName) { List<string> dataList = new List<string>(); String line; try { //Pass the file path and file name to the StreamReader constructor StreamReader sr = new StreamReader(fileName, Encoding.GetEncoding("gb2312")); //Read the first line of text line = sr.ReadLine(); //Continue to read until you reach end of file while (line != null) { dataList.Add(line); //Read the next line line = sr.ReadLine(); } //close the file sr.Close(); } catch (Exception e) { dataList = null; } return dataList; }
//检查文件是否存在 if (!File.Exists(filepath)) return null; //读起文件流 FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Read); StreamReader m_streamRead = new StreamReader(fs, System.Text.Encoding.Default); m_streamRead.BaseStream.Seek(0, SeekOrigin.Begin); string s = m_streamRead.ReadToEnd(); m_streamRead.Close(); fs.Close(); string[] sList=s.Split('\n');//再把数组给List绑定
using System.io;fileStream fs=new fileStream ("yourtxt.txt",fileMode.Create);
StreamWirte sw=new StreamWirte (fs);
sw.WriteLine(textbox.Text);
sw.Close();
fs.Close();
using System.io;fileStream fs=new fileStream ("yourtxt.txt",fileMode.Open);
StreamRead sr=new StreamRead (fs);
sr.ReadLine(listbox.Text);
sr.Close();
fs.Close();重要的部分 这代码.不出来 我大小写没有注意 你注意下~
StreamWriter sw = new StreamWriter( @"C:\temp123.txt");
sw.WriteLine("----------------hello----------------");
sw.WriteLine("内容");
sw.WriteLine("----------------hello----------------");
sw.Flush();
sw.Close();//读取
System.IO.StreamReader st;
st = new System.IO.StreamReader(@"C:\temp123.txt", System.Text.Encoding.UTF8);//UTF8为编码
this.textBox1.Text = st.ReadToEnd();
后边参数为true就是 有新数据继续写
要是为false 就是 后边的数据覆盖前边的
我也是用的StreamWriter和StreamReader
{
string ss=sr.ReadLine();
this.listBox1.Items.add(ss);
}
while(!sr.EndOfStream)
{
this.listBox1.Items.Add(sr.ReadLine());
}
FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "table.txt", FileMode.OpenOrCreate);
fs.Flush();
fs.Close();
//写入数据
StreamWriter sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "table.txt", false, Encoding.Default);
{ FileStream fs = (!File.Exists(filepath)) ? new FileStream(filepath, FileMode.Create) : File.Open(filepath, FileMode.Append);
//获得字节数组
byte[] data = new UTF8Encoding().GetBytes(str+'\n');
//开始写入
fs.Write(data, 0, data.Length);
//清空缓冲区、关闭流
fs.Flush();
fs.Close();
}//调用WriteFile(@"c:\ss.txt","给我分啊")
StreamWriter oStreamWriter = new StreamWriter(oFileStream, Encoding.Default);
oStreamWriter.Write("要写入内容");
oStreamWriter.WriteLine();
oStreamWriter.Close();
oFileStream.Close();
读取oFileStream = new FileStream("文件路径", FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
StreamReader oStreamReader = new StreamReader(oFileStream, Encoding.Default);
string _Text = oStreamReader.ReadToEnd();
oStreamReader.Close();
oFileStream.Close();
读取时应是FileMode.Open,FileAccess.Read
唉直接把上面的写入的复制下来了。
string[] File.ReadAllLine(filepath)
/// 写数据到文件
/// </summary>
/// <param name="strDataList">行数据列表</param>
/// <param name="filename">文件名</param>
/// <returns>是否成功</returns>
public static bool WriteToFile(List<string> strDataList,string filename)
{
try
{ //Pass the filepath and filename to the StreamWriter Constructor
// StreamWriter sw = new StreamWriter(filename);
StreamWriter sw = new StreamWriter(filename,false,Encoding.GetEncoding("gb2312")); sw.Write("", false); //Write a line of text
foreach (string item in strDataList)
{
sw.WriteLine(item, true);
} //Close the file
sw.Close();
return true;
}
catch (Exception e)
{
return false;
}
} /// <summary>
/// 从文件获取数据
/// </summary>
/// <param name="fileName">文件名</param>
/// <returns>行数据列表</returns>
public static List<string> ReadFromFile(string fileName)
{
List<string> dataList = new List<string>();
String line;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader(fileName, Encoding.GetEncoding("gb2312")); //Read the first line of text
line = sr.ReadLine(); //Continue to read until you reach end of file
while (line != null)
{
dataList.Add(line);
//Read the next line
line = sr.ReadLine();
} //close the file
sr.Close();
}
catch (Exception e)
{
dataList = null;
}
return dataList;
}
if (!File.Exists(filepath)) return null;
//读起文件流
FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate, FileAccess.Read);
StreamReader m_streamRead = new StreamReader(fs, System.Text.Encoding.Default);
m_streamRead.BaseStream.Seek(0, SeekOrigin.Begin);
string s = m_streamRead.ReadToEnd();
m_streamRead.Close();
fs.Close();
string[] sList=s.Split('\n');//再把数组给List绑定
StreamWirte sw=new StreamWirte (fs);
sw.WriteLine(textbox.Text);
sw.Close();
fs.Close();
上面是写入下面上读取到ListBox
fileStream fs=new fileStream ("yourtxt.txt",fileMode.Open);
StreamRead sr=new StreamRead (fs);
listbox.text=sr.ReadToEnd()
sr.Close();
fs.Close();
private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);
//参数说明:section:INI文件中的段落;key:INI文件中的关键字;val:INI文件中关键字的数值;filePath:INI文件的完整的路径和名称。C#申明INI文件的读操作函数GetPrivateProfileString():
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath);
//参数说明:section:INI文件中的段落名称;key:INI文件中的关键字;def:无法读取时候时候的缺省数值;retVal:读取数值;size:数值的大小;filePath:INI文件的完整路径和名称。
写入、读取WritePrivateProfileString(Section,Key,Value,this.inipath);//写入 public string IniReadValue(string Section,string Key)//度取
{
StringBuilder temp = new StringBuilder(200);
int i = GetPrivateProfileString(Section,Key,"",temp,200,this.inipath);
return temp.ToString();
}
文件格式如下:
[段落名1]
关键字1=值1
关键字2=值2
关键字3=值3
[段落名2]
关键字1=值1
关键字2=值2
/// 将存贮在文本文件中的数据绑定到DropDownList中 test,test
/// </summary>
/// <param name="drdlst">下拉菜单</param>
/// <param name="filePath">虚拟路径</param>
public void Drdlst_BindDataByTxt1(DropDownList drdlst, string filePath)
{
string fileName = HttpContext.Current.Server.MapPath(filePath);
string content = "";
StreamReader sr = null;
try
{
//打开文件并显示其内容
sr = new StreamReader(fileName, System.Text.Encoding.Default);
for (string line = sr.ReadLine(); line != null; line = sr.ReadLine())
{
content += line.ToString();
}
string[] arr = content.Split(',');
for (int i = 0; i < arr.Length; i++)
{
ListItem li = new ListItem();
li.Text = arr[i].ToString();
li.Value = arr[i].ToString();
drdlst.Items.Add(li);
}
}
catch (IOException ee)
{
HttpContext.Current.Response.Write("<script>alert(" + ee.Message + ")</script>");
}
finally
{
if (sr != null)
{
sr.Close();
}
}
} /// <summary>
/// 获取txt中信息
/// </summary>
/// <param name="filePath">虚拟路径</param>
/// <returns></returns>
public string GetTxtInfo(string filePath)
{
string fileName = HttpContext.Current.Server.MapPath(filePath);
string str = "";
StreamReader sr = null;
try
{
sr = new StreamReader(fileName, System.Text.Encoding.Default);
for (string line = sr.ReadLine(); line != null; line = sr.ReadLine())
{
str += line.ToString();
}
}
catch (IOException ee)
{
HttpContext.Current.Response.Write("<script>alert(" + ee.Message + ")</script>");
}
finally
{
if (sr != null)
{
sr.Close();
}
} return str;
} /// <summary>
/// 保存数据到txt中
/// </summary>
/// <param name="str">要保存的数据</param>
/// <param name="filePath">虚拟路径</param>
public void SaveTxtInfo(string str, string filePath)
{
string fileName = HttpContext.Current.Server.MapPath(filePath);
StreamWriter sw = null;
FileStream oFileStream = null;
try
{
if (!System.IO.File.Exists(fileName))
{
oFileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.ReadWrite);
}
else
{
oFileStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
} sw = new StreamWriter(oFileStream, Encoding.Default);
sw.Write(str);
sw.WriteLine();
}
catch (IOException ee)
{
HttpContext.Current.Response.Write("<script>alert(" + ee.Message + ")</script>");
}
finally
{
if (sw != null)
{
sw.Close();
oFileStream.Close();
}
}
}
StreamWriter sw = new StreamWriter( @"C:\temp123.txt");
sw.WriteLine("----------------hello----------------");
sw.WriteLine("内容");
sw.WriteLine("----------------hello----------------");
sw.Flush();
sw.Close();//读取
System.IO.StreamReader st;
st = new System.IO.StreamReader(@"C:\temp123.txt", System.Text.Encoding.UTF8);//UTF8为编码
this.textBox1.Text = st.ReadToEnd();
{
while (!SrmR.EndOfStream)
{
...
}
}
//{
// return;
// string path = "~/Web/Share/SqlLog.txt";
// FileStream fs = null;
// StreamWriter sw = null;
// try
// {
// if (File.Exists(Server.MapPath(path)))
// {
// fs = new FileStream(Server.MapPath(path), FileMode.Append);
// }
// else
// {
// fs = new FileStream(Server.MapPath(path), FileMode.Create);
// } // sw = new StreamWriter(fs, System.Text.Encoding.Default);
// sw.Write(DateTime.Now.ToString());
// sw.Write("\r\n" + where + "\r\n\r\n");
// }
// catch (Exception e)
// {
// throw e;
// }
// finally
// {
// sw.Close();
// fs.Close();
// } //}
{
string ss=sr.ReadLine();
this.listBox1.Items.add(ss);
}