C#编程实用技巧:轻松实现对文件的操作
C#编程实用技巧:轻松实现对文件的操作和Java一样,C#提供的类库能够轻松实现对文件的操作。下面就给出代码示例,大家可以参考一下。
C#写入读出文本文件
string fileName =@cI.txt;
StreamReader sr = new StreamReader(fileName); string str=sr.ReadLine (); sr.close();
StreamWriterrw=File.CreateText(Server.MapPath(.)+myText.txt);
rw.WriteLine(写入);
rw.WriteLine(abc);
rw.WriteLine(.NET笔记);
rw.Flush();
rw.Close();
打开文本文件
StreamReadersr=File.OpenText(Server.MapPath(.)+myText.txt);
StringBuilderoutput=newStringBuilder();
stringrl;
while((rl=sr.ReadLine())!=null)
...{
output.Append(rl+);
}
lblFile.Text=output.ToString();
sr.Close();
C#追加文件
StreamWritersw=File.AppendText(Server.MapPath(.)+myText.txt);
sw.WriteLine(追逐理想);
sw.WriteLine(kzlll);
sw.WriteLine(.NET笔记);
sw.Flush();
sw.Close();
C#拷贝文件
stringOrignFile,NewFile;
OrignFile=Server.MapPath(.)+myText.txt;
NewFile=Server.MapPath(.)+myTextCopy.txt;
File.Copy(OrignFile,NewFile,true);
C#删除文件
stringdelFile=Server.MapPath(.)+myTextCopy.txt;
File.Delete(delFile);
C#移动文件
stringOrignFile,NewFile;
OrignFile=Server.MapPath(.)+myText.txt;
NewFile=Server.MapPath(.)+myTextCopy.txt;
File.Move(OrignFile,NewFile);
C#创建目录
创建目录csixAge
DirectoryInfod=Directory.CreateDirectory(csixAge);
d1指向csixAgesixAge1
DirectoryInfod1=d.CreateSubdirectory(sixAge1);
d2指向csixAgesixAge1sixAge1_1
DirectoryInfod2=d1.CreateSubdirectory(sixAge1_1);
将当前目录设为csixAge
Directory.SetCurrentDirectory(csixAge);
创建目录csixAgesixAge2
Directory.CreateDirectory(sixAge2);
创建目录csixAgesixAge2sixAge2_1
Directory.CreateDirectory(sixAge2sixAge2_1);
但是,在对txt文件读的操作中貌似没问题。因为代码能实现文件的读操作,但是所读txt文件包含中文的时候就以乱码显示。查了半天资料,看似复杂的问题其实很简单就能解决,稍微改动一下即可:
StreamReader sr = new StreamReader(fileName,Encoding.GetEncoding(gb2312));
资料引用:http://www.now.cn/
http://game.ali213.net/images/common/sigline.gif
时代互联|域名注册|虚拟主机|主机|企业邮箱|服务器租用|中文域名注册|VPS主机|
时代互联是中国顶级域名注册商,是中国首批经ICANN和CNNIC认证的域名注册商,也是中国专业的虚拟主机和服务器租用托管服务提供商,多年专注于域名注册,虚拟主机,VPS主机,企业邮箱,服务器租用,企业短信平台,网站建设等网络服务。
http://www.now.cn/ 但XNA对中文的支持问题只能让人暂时望而却步了吧
我觉得直接操作文件和C语言差别不大了吧? 跟Java不一样,C#里要是就地对文件操作的话(“就地”就是说在同一个地方打开文件,读/写数据,然后关闭文件),一般会使用using语句来处理资源管理。
所以与其写:
StreamReader in = new StreamReader(fileName);
string str = in.ReadLine();
in.close();
一般会写:
string str;
using (StreamReader in = File.OpenText(fileName)) {
str = in.ReadLine();
}
这样,using语句会生成一个finally块,在里面调用StreamReader.Dispose(),也就关掉了流。
不在finally块里调用善后的相关方法的话,如果出了异常就没人善后了。每次写finally也很麻烦,所以有using帮我们做。
页:
[1]