Csharp文件操作集锦

发布时间:2011-05-26 07:54:37   来源:文档文库   
字号:

C#文件操作集锦:追加、复制、删除与文件夹操作

C#文件操作:C#追加文件

1. StreamWriter sw = File.AppendText(  

2. Server.MapPath(".")+"\\myText.txt");   

3. sw.WriteLine("追逐理想");   

4. sw.WriteLine("kzlll");   

5. sw.WriteLine(".NET笔记");   

6. sw.Flush();   

7. sw.Close();   

C#文件操作:C#拷贝文件

1. string OrignFile,NewFile;   

2. OrignFile = Server.MapPath(  

3. ".")+"\\myText.txt";   

4. NewFile = Server.MapPath(  

5. ".")+"\\myTextCopy.txt";   

6. File.Copy(OrignFile,NewFile,true);   

C#文件操作:C#删除文件

1. string delFile = Server.MapPath(  

2. ".")+"\\myTextCopy.txt";   

3. File.Delete(delFile);   

C#文件操作:C#移动文件

1. string OrignFile,NewFile;   

2. OrignFile = Server.MapPath(  

3. ".")+"\\myText.txt";   

4. NewFile = Server.MapPath(  

5. ".")+"\\myTextCopy.txt";   

6. File.Move(OrignFile,NewFile);   

C#文件操作:C#创建目录

1. // 创建目录c:\sixAge   

2. DirectoryInfo d=  

3. Directory.CreateDirectory("c:\\sixAge");   

4. // d1指向c:\sixAge\sixAge1   

5. DirectoryInfo d1=  

6. d.CreateSubdirectory("sixAge1");   

7. // d2指向c:\sixAge\sixAge1\sixAge1_1   

8. DirectoryInfo d2=  

9. d1.CreateSubdirectory("sixAge1_1");   

10. // 将当前目录设为c:\sixAge   

11. Directory.SetCurrentDirectory("  

12. c:\\sixAge");   

13. // 创建目录c:\sixAge\sixAge2   

14. Directory.CreateDirectory("  

15. sixAge2");   

16. // 创建目录c:\sixAge\sixAge2\sixAge2_1   

17. Directory.CreateDirectory("  

18. sixAge2\\sixAge2_1");  

递归删除文件夹及文件

1. %@PageLanguage=C#%  

2. %@Importnamespace="System.IO"%  

3. Scriptrunat=server  

4. publicvoidDeleteFolder(stringdir)  

5. {  

6. if(Directory.Exists(dir))//如果  

7. 存在这个文件夹删除之  

8. {  

9. foreach(stringdinDirectory.  

10. GetFileSystemEntries(dir))  

11. {  

12. if(File.Exists(d))  

13. File.Delete(d);//直接删除其中的文件  

14. else 

15. DeleteFolder(d);//递归删除子文件夹  

16. }  

17. Directory.Delete(dir);//删除已空文件夹  

18. Response.Write(dir+"文件夹删除成功");  

19. }  

20. else 

21. Response.Write(dir+"该文件夹不存在");//如果  

22. 文件夹不存在则提示  

23. }  

24. protectedvoidPage_Load(Object  

25. sender,EventArgse)  

26. {  

27. stringDir="D:\\gbook\\11";  

28. DeleteFolder(Dir);//调用函数删除文件夹  

29. }  

30.  

31.  

32. //========================================  

33. //实现一个静态方法将指定文件夹下面的  

34. 所有内容copy到目标文件夹下面  

35. //如果目标文件夹为只读属性就会报错。  

36. //April18April2005InSTU  

37. //========================================  

38. publicstaticvoidCopyDir(stringsrcPath,  

39. stringaimPath)  

40. {  

41. try  

42. {  

43. //检查目标目录是否以目录分割字  

44. 符结束如果不是则添加之  

45. if(aimPath[aimPath.Length-1]!=  

46. Path.DirectorySeparatorChar)  

47. aimPath+=Path.DirectorySeparatorChar;  

48. //判断目标目录是否存在如果不存在则新建之  

49. if(!Directory.Exists(aimPath))Directory.  

50. CreateDirectory(aimPath);  

51. //得到源目录的文件列表,  

52. 该里面是包含文件以及目录路径的一个数组  

53. //如果你指向copy目标文件下面的文件  

54. 而不包含目录请使用下面的方法  

55. //string[]fileList=  

56. Directory.GetFiles(srcPath);  

57. string[]fileList=  

58. Directory.GetFileSystemEntries(srcPath);  

59. //遍历所有的文件和目录  

60. foreach(stringfileinfileList)  

61. {  

62. //先当作目录处理如果存在这个  

63. 目录就递归Copy该目录下面的文件  

64. if(Directory.Exists(file))  

65. CopyDir(file,aimPath+Path.GetFileName(file));  

66. //否则直接Copy文件  

67. else 

68. File.Copy(file,aimPath+Path.GetFileName(  

69. file),true);  

70. }  

71. }  

72. catch(Exceptione)  

73. {  

74. MessageBox.Show(e.ToString());  

75. }  

76. }  

77. //========================================  

78. //实现一个静态方法将指定文  

79. 件夹下面的所有内容Detele  

80. //测试的时候要小心操作,删除之后无法恢复。  

81. //April18April2005InSTU  

82. //========================================  

83. publicstaticvoidDeleteDir(stringaimPath)  

84. {  

85. try  

86. {  

87. //检查目标目录是否以目录分割字  

88. 符结束如果不是则添加之  

89. if(aimPath[aimPath.Length-1]!=  

90. Path.DirectorySeparatorChar)  

91. aimPath+=Path.DirectorySeparatorChar;  

92. //得到源目录的文件列表,  

93. 该里面是包含文件以及目录路径的一个数组  

94. //如果你指向Delete目标文件下面的  

95. 文件而不包含目录请使用下面的方法  

96. //string[]fileList=  

97. Directory.GetFiles(aimPath);  

98. string[]fileList=  

99. Directory.GetFileSystemEntries(aimPath);  

100. //遍历所有的文件和目录  

101. foreach(stringfileinfileList)  

102. {  

103. //先当作目录处理如果存在这个  

104. 目录就递归Delete该目录下面的文件  

105. if(Directory.Exists(file))  

106. {  

107. DeleteDir(aimPath+Path.GetFileName(file));  

108. }  

109. //否则直接Delete文件  

110. else 

111. {  

112. File.Delete(aimPath+Path.GetFileName(file));  

113. }  

114. }  

115. //删除文件夹  

116. System.IO.Directory.Delete(aimPath,true);  

117. }  

118. catch(Exceptione)  

119. {  

120. MessageBox.Show(e.ToString());  

121. }  

122. }  

123.  

124. 需要引用命名空间:  

125. usingSystem.IO;  

126.  

127. /**////summary  

128. ///拷贝文件夹(包括子文件夹)到指定文件夹下,  

129. 源文件夹和目标文件夹均需绝对路径.  

130. 格式:CopyFolder(源文件夹,目标文件夹);  

131. ////summary  

132. ///paramname="strFromPath"〉〈/param  

133. ///paramname="strToPath"〉〈/param  

134.  

135. //----------------------------------------  

136. //作者:明天去要饭QQ:305725744  

137. //----------------------------------------  

138. publicstaticvoidCopyFolder(stringstrFromPath,  

139. stringstrToPath)  

140. {  

141. //如果源文件夹不存在,则创建  

142. if(!Directory.Exists(strFromPath))  

143. {  

144. Directory.CreateDirectory(strFromPath);  

145. }  

146.  

147. //取得要拷贝的文件夹名  

148. stringstrFolderName=strFromPath.Substring(  

149. strFromPath.LastIndexOf("\\")+1,strFromPath.  

150. Length-strFromPath.LastIndexOf("\\")-1);  

151.  

152. //如果目标文件夹中没有源文件夹则在  

153. 目标文件夹中创建源文件夹  

154. if(!Directory.Exists(strToPath+"\\" 

155. +strFolderName))  

156. {  

157. Directory.CreateDirectory(strToPath+"\\" 

158. +strFolderName);  

159. }  

160. //创建数组保存源文件夹下的文件名  

161. string[]strFiles=Directory.GetFiles(strFromPath);  

162.  

163. //循环拷贝文件  

164. for(inti=0;istrFiles.Length;i++)  

165. {  

166. //取得拷贝的文件名,只取文件名,地址截掉。  

167. stringstrFileName=strFiles[i].Substring(  

168. strFiles[i].LastIndexOf("\\")+1,  

169. strFiles[i].Length-strFiles[i].  

170. LastIndexOf("\\")-1);  

171. //开始拷贝文件,true表示覆盖同名文件  

172. File.Copy(strFiles[i],strToPath+"\\" 

173. +strFolderName+"\\"+strFileName,true);  

174. }  

175.  

176. //创建DirectoryInfo实例  

177. DirectoryInfodirInfo=newDirectoryInfo(  

178. strFromPath);  

179. //取得源文件夹下的所有子文件夹名称  

180. DirectoryInfo[]ZiPath=dirInfo.GetDirectories();  

181. for(intj=0;jZiPath.Length;j++)  

182. {  

183. //获取所有子文件夹名  

184. stringstrZiPath=strFromPath+"\\"+  

185. ZiPath[j].ToString();  

186. //把得到的子文件夹当成新的源文件夹,  

187. 从头开始新一轮的拷贝  

188. CopyFolder(strZiPath,strToPath+"\\"+  

189. strFolderName);  

190. }  

191. }  

C#文件操作:读取文本文件

1. 1/**//// summary  

2. 2/// 读取文本文件  

3. 3/// /summary  

4. 4private void ReadFromTxtFile()  

5. 5{  

6. 6    if(filePath.PostedFile.  

7. FileName != "")  

8. 7    {  

9. 8    txtFilePath =  

10. filePath.PostedFile.FileName;  

11. 9    fileExtName =   

12. txtFilePath.Substring(txtFilePath.  

13. LastIndexOf(".")+1,3);  

14. 10  

15. 11   if(fileExtName !="txt" &&   

16. fileExtName != "TXT")  

17. 12   {  

18. 13   Response.Write("请选择文本文件");  

19. 14   }  

20. 15   else 

21. 16   {  

22. 17   StreamReader fileStream =   

23. new StreamReader(txtFilePath,Encoding.Default);  

24. 18   txtContent.Text = fileStream.ReadToEnd();  

25. 19   fileStream.Close();  

26. 20   }  

27. 21   }  

28. 22 } 

C#文件操作:获取文件列表

1. 1/**//// summary  

2. 2/// 获取文件列表  

3. 3/// /summary  

4. 4private void GetFileList()  

5. 5{  

6. 6  string strCurDir,FileName,FileExt;  

7. 7      

8. 8    /**////文件大小  

9. 9    long FileSize;  

10. 10      

11. 11    /**////最后修改时间;  

12. 12    DateTime FileModify;  

13. 13  

14. 14    /**////初始化  

15. 15    if(!IsPostBack)  

16. 16    {  

17. 17  /**////初始化时,默认为当前页面所在的目录  

18. 18     strCurDir = Server.MapPath(".");  

19. 19     lblCurDir.Text = strCurDir;  

20. 20     txtCurDir.Text = strCurDir;  

21. 21    }  

22. 22    else 

23. 23    {  

24. 24     strCurDir = txtCurDir.Text;  

25. 25     txtCurDir.Text = strCurDir;  

26. 26     lblCurDir.Text = strCurDir;  

27. 27    }  

28. 28    FileInfo fi;  

29. 29    DirectoryInfo dir;  

30. 30    TableCell td;  

31. 31    TableRow tr;  

32. 32    tr = new TableRow();  

33. 33      

34. 34    /**////动态添加单元格内容  

35. 35    td = new TableCell();  

36. 36    td.Controls.Add(new LiteralControl(  

37. "文件名"));  

38. 37    tr.Cells.Add(td);  

39. 38    td = new TableCell();  

40. 39    td.Controls.Add(new LiteralControl(  

41. "文件类型"));  

42. 40    tr.Cells.Add(td);  

43. 41    td = new TableCell();  

44. 42    td.Controls.Add(new LiteralControl(  

45. "文件大小"));  

46. 43    tr.Cells.Add(td);  

47. 44    td = new TableCell();  

48. 45    td.Controls.Add(new LiteralControl(  

49. "最后修改时间"));  

50. 46    tr.Cells.Add(td);  

51. 47  

52. 48    tableDirInfo.Rows.Add(tr);  

53. 49      

54. 50    /**////针对当前目录建立目录引用对象  

55. 51    DirectoryInfo dirInfo = new DirectoryInfo(  

56. txtCurDir.Text);  

57. 52      

58. 53    /**////循环判断当前目录下的文件和目录  

59. 54    foreach(FileSystemInfo fsi in dirInfo.  

60. GetFileSystemInfos())  

61. 55    {  

62. 56      FileName = "";  

63. 57      FileExt = "";  

64. 58      FileSize = 0;  

65. 59          

66. 60      /**////如果是文件  

67. 61      if(fsi is FileInfo)  

68. 62      {  

69. 63      fi = (FileInfo)fsi;  

70. 64              

71. 65      /**////取得文件名  

72. 66      FileName = fi.Name;  

73. 67              

74. 68     /**////取得文件的扩展名  

75. 69     FileExt = fi.Extension;  

76. 70              

77. 71    /**////取得文件的大小  

78. 72    FileSize = fi.Length;  

79. 73              

80. 74   /**////取得文件的最后修改时间  

81. 75   FileModify = fi.LastWriteTime;  

82. 76   }  

83. 77  

84. 78   /**////否则是目录  

85. 79   else 

86. 80    {  

87. 81    dir = (DirectoryInfo)fsi;  

88. 82              

89. 83     /**////取得目录名  

90. 84     FileName = dir.Name;  

91. 85              

92. 86     /**////取得目录的最后修改时间  

93. 87     FileModify = dir.LastWriteTime;  

94. 88              

95. 89     /**////设置文件的扩展名为"文件夹" 

96. 90    FileExt = "文件夹";  

97. 91     }  

98. 92          

99. 93    /**////动态添加表格内容  

100. 94        tr = new TableRow();  

101. 95        td = new TableCell();  

102. 96        td.Controls.Add(new LiteralControl(  

103. FileName));  

104. 97        tr.Cells.Add(td);  

105. 98        td = new TableCell();  

106. 99        td.Controls.Add(new LiteralControl(  

107. FileExt));  

108. 100        tr.Cells.Add(td);  

109. 101        td = new TableCell();  

110. 102        td.Controls.Add(new LiteralControl(  

111. FileSize.ToString()+"字节"));  

112. 103        tr.Cells.Add(td);  

113. 104        td = new TableCell();  

114. 105        td.Controls.Add(new LiteralControl(  

115. FileModify.ToString("yyyy-mm-dd hh:mm:ss")));  

116. 106        tr.Cells.Add(td);  

117. 107        tableDirInfo.Rows.Add(tr);  

118. 108    }  

119. 109} 

C#文件操作:读取日志文件

1. 1/**//// summary  

2. 2/// 读取日志文件  

3. 3/// /summary  

4. 4private void ReadLogFile()  

5. 5{  

6. 6    /**////从指定的目录以打  

7. 开或者创建的形式读取日志文件  

8. 7    FileStream fs =   

9. new FileStream(Server.MapPath("upedFile" 

10. )+"\\logfile.txt", FileMode.OpenOrCreate,   

11. FileAccess.Read);  

12. 8  

13. 9    /**////定义输出字符串  

14. 10    StringBuilder output =   

15. new StringBuilder();  

16. 11      

17. 12    /**////初始化该字符串的长度为0  

18. 13    output.Length = 0;  

19. 14      

20. 15    /**////为上面创建的文件流创建读取数据流  

21. 16    StreamReader read = new StreamReader(fs);  

22. 17      

23. 18    /**////设置当前流的起始位置为文件流的起始点  

24. 19    read.BaseStream.Seek(0, SeekOrigin.Begin);  

25. 20      

26. 21    /**////读取文件  

27. 22    while (read.Peek()  -1)   

28. 23    {  

29. 24        /**////取文件的一行内容并换行  

30. 25        output.Append(read.ReadLine() + "\n");  

31. 26    }  

32. 27      

33. 28    /**////关闭释放读数据流  

34. 29    read.Close();  

35. 30      

36. 31    /**////返回读到的日志文件内容  

37. 32    return output.ToString();  

38. 33} 

C#文件操作:写入日志文件

1. 1/**//// summary  

2. 2/// 写入日志文件  

3. 3/// /summary  

4. 4/// param name="input"〉〈/param  

5. 5private void WriteLogFile(string input)  

6. 6{      

7. 7    /**////指定日志文件的目录  

8. 8    string fname = Server.MapPath(  

9. "upedFile") + "\\logfile.txt";  

10. 9    /**////定义文件信息对象  

11. 10    FileInfo finfo = new FileInfo(fname);  

12. 11  

13. 12    /**////判断文件是否存在以及是否大于2K  

14. 13    if ( finfo.Exists && finfo.Length   

15.  2048 )  

16. 14    {  

17. 15        /**////删除该文件  

18. 16        finfo.Delete();  

19. 17    }  

20. 18    /**////创建只写文件流  

21. 19   using(FileStream fs = finfo.OpenWrite())  

22. 20    {  

23. 21   /**////根据上面创建的文件流创建写数据流  

24. 22   StreamWriter w = new StreamWriter(fs);  

25. 23          

26. 24    /**////设置写数据流的起始位置为文件流的末尾  

27. 25   w.BaseStream.Seek(0, SeekOrigin.End);  

28. 26          

29. 27    /**////写入“Log Entry :   

30. 28    w.Write("\nLog Entry : ");  

31. 29          

32. 30   /**////写入当前系统时间并换行  

33. 31    w.Write("{0} {1} \r\n", DateTime.Now.  

34. ToLongTimeString(),  

35. 32     DateTime.Now.ToLongDateString());  

36. 33          

37. 34    /**////写入日志内容并换行  

38. 35    w.Write(input + "\n");  

39. 36          

40. 37    /**////写入----------------“并换行  

41. 38    w.Write("------------------\n");  

42. 39          

43. 40  /**////清空缓冲区内容,并把缓冲区内容写入基础流  

44. 41   w.Flush();  

45. 42          

46. 43        /**////关闭写数据流  

47. 44        w.Close();  

48. 45    }  

49. 46} 

C#文件操作:创建HTML文件

1. 1/**//// summary  

2. 2/// 创建HTML文件  

3. 3/// /summary  

4. 4private void CreateHtmlFile()  

5. 5{      

6. 6    /**////定义和html标记数目一致的数组  

7. 7    string[] newContent = new string[5];  

8. 8    StringBuilder strhtml =   

9. new StringBuilder();  

10. 9    try   

11. 10    {  

12. 11    /**////创建StreamReader对象  

13. 12    using (StreamReader sr =   

14. new StreamReader(Server.MapPath("  

15. createHTML") + "\\template.html"))   

16. 13        {  

17. 14     String oneline;  

18. 15              

19. 16     /**////读取指定的HTML文件模板  

20. 17     while ((oneline = sr.ReadLine())   

21. != null)   

22. 18     {  

23. 19     strhtml.Append(oneline);  

24. 20            }  

25. 21     sr.Close();  

26. 22        }  

27. 23    }  

28. 24    catch(Exception err)  

29. 25    {  

30. 26        /**////输出异常信息  

31. 27        Response.Write(err.ToString());  

32. 28    }  

33. 29    /**////为标记数组赋值  

34. 30    newContent[0] = txtTitle.Text;//标题  

35. 31    newContent[1] = "BackColor='  

36. #cccfff'";//背景色  

37. 32    newContent[2] = "#ff0000";//字体颜色  

38. 33    newContent[3] = "100px";//字体大小  

39. 34    newContent[4] = txtContent.Text;//主要内容  

40. 35  

41. 36    /**////根据上面新的内容生成html文件  

42. 37    try  

43. 38    {  

44. 39    /**////指定要生成的HTML文件  

45. 40    string fname = Server.MapPath(  

46. "createHTML") +"\\" + DateTime.Now.ToString(  

47. "yyyymmddhhmmss") + ".html";  

48. 41          

49. 42   /**////替换html模版文件里的标记为新的内容  

50. 43   for(int i=0;i  5;i++)  

51. 44   {  

52. 45    strhtml.Replace("$htmlkey["+i+"]",newContent[i]);  

53. 46    }  

54. 47    /**////创建文件信息对象  

55. 48    FileInfo finfo = new FileInfo(fname);  

56. 49          

57. 50    /**////以打开或者写入的形式创建文件流  

58. 51    using(FileStream fs = finfo.OpenWrite())  

59. 52   {  

60. 53    /**////根据上面创建的文件流创建写数据流  

61. 54  StreamWriter sw = new StreamWriter(fs,System.  

62. Text.Encoding.GetEncoding("GB2312"));  

63. 55              

64. 56   /**////把新的内容写到创建的HTML页面中  

65. 57   sw.WriteLine(strhtml);  

66. 58   sw.Flush();  

67. 59   sw.Close();  

68. 60   }  

69. 61          

70. 62   /**////设置超级链接的属性  

71. 63  hyCreateFile.Text =   

72. DateTime.Now.ToString("yyyymmddhhmmss")+".html";  

73. 64  hyCreateFile.NavigateUrl = "  

74. createHTML/"+DateTime.Now.ToString(" 

75. yyyymmddhhmmss")+".html";  

76. 65    }  

77. 66    catch(Exception err)  

78. 67    {   

79. 68        Response.Write (err.ToString());  

80. 69    }  

81. 70 }  

本文来源:https://www.2haoxitong.net/k/doc/7a8e35976bec0975f465e2ca.html

《Csharp文件操作集锦.doc》
将本文的Word文档下载到电脑,方便收藏和打印
推荐度:
点击下载文档

文档为doc格式