c#操作文件

//读取txt文件内容

StreamReader NameIntxtSr = new StreamReader(文件路径, Encoding.Default);
string NameIntxt = File.ReadAllText(文件路径, Encoding.Default);

//写入txt文件

StreamWriter swter = new StreamWriter(文件绝对路径, false, Encoding.Default);

sw.WriteLine();

//读取excel文件

DataTable myT = ExcelToDataTable(文件路径, "sheet1");//使用

public DataTable ExcelToDataTable(string strExcelFileName, string strSheetName)//实现
{
//源的定义
string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strExcelFileName + ";Extended Properties="Excel 12.0;HDR=YES;IMEX=1"";
//Sql语句
string strExcel = "select * from [sheet1$]";
//连接数据源
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
//适配到数据源
OleDbDataAdapter adapter = new OleDbDataAdapter(strExcel, strConn);
adapter.Fill(ds, strSheetName);
conn.Close();
return ds.Tables[strSheetName];
}

//读取,ini文件

[DllImport("kernel32")]//返回0表示失败,非0为成功
private static extern long WritePrivateProfileString(string section, string key,
string val, string filePath);

[DllImport("kernel32")]//返回取得字符串缓冲区的长度
private static extern long GetPrivateProfileString(string section, string key,
string def, StringBuilder retVal, int size, string filePath);

DirectoryInfo foldinfo = new DirectoryInfo(文件路径);

System.Text.StringBuilder temp = new System.Text.StringBuilder(255);
GetPrivateProfileString("Towns", "id", "", temp, 255, IniPath);//读取.ini文件中的id字段的值
LastDatat.id = temp.ToString();

//写入.ini文件

WritePrivateProfileString("Towns", "button", "true", IniPath2);//在ini文件写入 button=true

原文地址:https://www.cnblogs.com/yyangjing/p/9554102.html