当前位置:网站首页>C file and folder input / output stream code
C file and folder input / output stream code
2022-07-27 18:53:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm the king of the whole stack
1、 Create a text file
1 public class FileClass
2 {
3 public static void Main()
4 {
5 WriteToFile();
6 }
7 static void WriteToFile()
8 {
9 StreamWriter SW;
10 SW = File.CreateText(@"c:\MyTextFile.txt");
11 SW.WriteLine("God is greatest of them all");
12 SW.WriteLine("This is second line");
13 SW.Close();
14 Console.WriteLine("File Created SucacessFully");
15 }
16 } 2、 Reading documents
1 public class FileClass
2 {
3 public static void Main()
4 {
5 ReadFromFile(@"c:\MyTextFile.txt");
6 }
7 static void ReadFromFile(string filename)
8 {
9 StreamReader SR;
10 string S;
11 SR = File.OpenText(filename);
12 S = SR.ReadLine();
13 while (S != null)
14 {
15 Console.WriteLine(S);
16 S = SR.ReadLine();
17 }
18 SR.Close();
19 }
20 }
21
22
23
24 public class FileClass
25 {
26 public static void Main()
27 {
28 AppendToFile();
29 }
30 static void AppendToFile()
31 {
32 StreamWriter SW;
33 SW = File.AppendText(@"C:\MyTextFile.txt");
34 SW.WriteLine("This Line Is Appended");
35 SW.Close();
36 Console.WriteLine("Text Appended Successfully");
37 }
38 }3、 Additional operations
C# Additional documents
1 StreamWriter sw = File.AppendText(Server.MapPath(".")+"\\myText.txt");
2 sw.WriteLine(" Pursue ideals ");
3 sw.WriteLine("http://www.cnblogs.com/roucheng/");
4 sw.WriteLine(".NET note ");
5 sw.Flush();
6 sw.Close();C# Copy files
1 string OrignFile,NewFile;
2 OrignFile = Server.MapPath(".")+"\\myText.txt";
3 NewFile = Server.MapPath(".")+"\\myTextCopy.txt";
4 File.Copy(OrignFile,NewFile,true);C# Delete file string delFile = Server.MapPath(“.”)+”\\myTextCopy.txt”; File.Delete(delFile);
C# Moving files
1 string OrignFile,NewFile;
2 OrignFile = Server.MapPath(".")+"\\myText.txt";
3 NewFile = Server.MapPath(".")+"\\myTextCopy.txt";
4 File.Move(OrignFile,NewFile);C# Create directory
1 // Create directory c:\sixAge
2 DirectoryInfo d=Directory.CreateDirectory("c:\\sixAge");
3 // d1 Point to c:\sixAge\sixAge1
4 DirectoryInfo d1=d.CreateSubdirectory("sixAge1");
5 // d2 Point to c:\sixAge\sixAge1\sixAge1_1
6 DirectoryInfo d2=d1.CreateSubdirectory("sixAge1_1");
7 // Set the current directory to c:\sixAge
8 Directory.SetCurrentDirectory("c:\\sixAge");
9 // Create directory c:\sixAge\sixAge2
10 Directory.CreateDirectory("sixAge2");
11 // Create directory c:\sixAge\sixAge2\sixAge2_1
12 Directory.CreateDirectory("sixAge2\\sixAge2_1");Delete folder and file recursively <%@ Page Language=C#%> <%@ Import namespace=”System.IO”%> <Script runat=server> public void DeleteFolder(string dir) { if (Directory.Exists(dir)) // If this folder exists, delete it { foreach(string d in Directory.GetFileSystemEntries(dir)) { if(File.Exists(d)) File.Delete(d); // Delete the files directly else DeleteFolder(d); // Recursively delete subfolders } Directory.Delete(dir); // Delete empty folder Response.Write(dir+” Folder deleted successfully ”); } else Response.Write(dir+” The folder does not exist ”); // If the folder does not exist, you will be prompted }
protected void Page_Load (Object sender ,EventArgs e) { string Dir=”D:\\gbook\\11″; DeleteFolder(Dir); // Call the function to delete the folder }
// ====================================================== // Implement a static method that will specify all the contents under the folder copy Go to the destination folder // If the target folder is read-only, an error will be reported . // April 18April2005 In STU // ====================================================== public static void CopyDir(string srcPath,string aimPath) { try { // Check whether the target directory ends with a directory split character. If not, add if(aimPath[aimPath.Length-1] != Path.DirectorySeparatorChar) aimPath += Path.DirectorySeparatorChar; // Determine whether the target directory exists. If not, create a new one if(!Directory.Exists(aimPath)) Directory.CreateDirectory(aimPath); // Get the file list of the source directory , It contains an array of files and directory paths // If you point to copy The file below the target file does not contain the directory. Please use the following method // string[] fileList = Directory.GetFiles(srcPath); string[] fileList = Directory.GetFileSystemEntries(srcPath); // Traverse all files and directories foreach(string file in fileList) { // First, treat it as a directory. If there is a directory, it will be recursive Copy Files under this directory if(Directory.Exists(file)) CopyDir(file,aimPath+Path.GetFileName(file)); // Otherwise directly Copy file else File.Copy(file,aimPath+Path.GetFileName(file),true); } } catch (Exception e) { MessageBox.Show (e.ToString()); } }
// ====================================================== // Implement a static method that will specify all the contents under the folder Detele // Be careful when testing , Can't recover after deleting . // April 18April2005 In STU // ====================================================== public static void DeleteDir(string aimPath) { try { // Check whether the target directory ends with a directory split character. If not, add if(aimPath[aimPath.Length-1] != Path.DirectorySeparatorChar) aimPath += Path.DirectorySeparatorChar; // Get the file list of the source directory , It contains an array of files and directory paths // If you point to Delete The file below the target file does not contain the directory. Please use the following method // string[] fileList = Directory.GetFiles(aimPath); string[] fileList = Directory.GetFileSystemEntries(aimPath); // Traverse all files and directories foreach(string file in fileList) { // First, treat it as a directory. If there is a directory, it will be recursive Delete Files under this directory if(Directory.Exists(file)) { DeleteDir(aimPath+Path.GetFileName(file)); } // Otherwise directly Delete file else { File.Delete (aimPath+Path.GetFileName(file)); } } // Delete folder System.IO .Directory .Delete (aimPath,true); } catch (Exception e) { MessageBox.Show (e.ToString()); } }
You need to reference a namespace : using System.IO;
1 //// <summary>
2 /// Copy folder ( Include subfolders ) To the specified folder , Both source and destination folders need absolute paths . Format : CopyFolder( Source folder , Destination folder );
3 /// </summary>
4 /// <param name="strFromPath"></param>
5 /// <param name="strToPath"></param>
6
7 //--------------------------------------------------
8 //http://www.cnblogs.com/roucheng/
9 //---------------------------------------------------
10
11 public static void CopyFolder(string strFromPath,string strToPath)
12 {
13 // If the source folder does not exist , Create
14 if (!Directory.Exists(strFromPath))
15 {
16 Directory.CreateDirectory(strFromPath);
17 }
18
19 // Get the folder name to copy
20 string strFolderName = strFromPath.Substring(strFromPath.LastIndexOf("\\") + 1,strFromPath.Length - strFromPath.LastIndexOf("\\") - 1);
21
22 // If there is no source folder in the destination folder, create the source folder in the destination folder
23 if (!Directory.Exists(strToPath + "\\" + strFolderName))
24 {
25 Directory.CreateDirectory(strToPath + "\\" + strFolderName);
26 }
27 // Create an array to save the file name in the source folder
28 string[] strFiles = Directory.GetFiles(strFromPath);
29
30 // Copy the file in a loop
31 for(int i = 0;i < strFiles.Length;i++)
32 {
33 // Get the file name of the copy , Just take the file name , Address cut off .
34 string strFileName = strFiles[i].Substring(strFiles[i].LastIndexOf("\\") + 1,strFiles[i].Length - strFiles[i].LastIndexOf("\\") - 1);
35 // Start copying files ,true Indicates overwriting a file with the same name
36 File.Copy(strFiles[i],strToPath + "\\" + strFolderName + "\\" + strFileName,true);
37 }
38
39 // establish DirectoryInfo example
40 DirectoryInfo dirInfo = new DirectoryInfo(strFromPath);
41 // Get the names of all subfolders under the source folder
42 DirectoryInfo[] ZiPath = dirInfo.GetDirectories();
43 for (int j = 0;j < ZiPath.Length;j++)
44 {
45 // Get all subfolder names
46 string strZiPath = strFromPath + "\\" + ZiPath[j].ToString();
47 // Treat the obtained subfolder as a new source folder , Start a new round of copies from scratch
48 CopyFolder(strZiPath,strToPath + "\\" + strFolderName);
49 }
50 }Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/120705.html Link to the original text :https://javaforall.cn
边栏推荐
- 图文结合,完美解释MySQL逻辑备份的实现流程
- Uni app label jump
- js中的函数与DOM获取元素和事件属性的使用
- V-bind and V-for
- 兆骑科创海内外引进高层次人才,创新创业项目对接
- How to send external mail to the company mailbox server on the Intranet
- [yuntu said] 249 mobile application security service - app's physical examination center, comprehensive testing, safe on the road!
- Part of speech list of common words
- org.gradle.api. UncheckedIOException: Could not load properties for module ‘gradle-kotlin-dsl‘ from C
- Run the uniapp to the mobile phone (real machine debugging)
猜你喜欢

MySQL 03 高级查询(一)

js实现简易表单验证与全选功能

Quick access to website media resources

你想得到想不到的MySQL面试题都在这了(2022最新版)

微信支付及支付回调

What should I do if MySQL master-slave replication data is inconsistent?

Hbuilder submission code

「MySQL那些事」一文详解索引原理

你有没有在MySQL的order by上栽过跟头

The combination of text and words perfectly explains the implementation process of MySQL logical backup
随机推荐
Wechat applet obtains openid, sessionkey, unionid
面试官:你觉得你最大的缺点是什么?
What does the number of network request interface layers (2/3 layers) mean
Knowledge map - Jieba, pyhanlp, smoothnlp tools to realize Chinese word segmentation (part of speech)
was not registered for synchronization because synchronization is not active[已解决]
图文结合,完美解释MySQL逻辑备份的实现流程
百度地图技术概述,及基本API与WebApi的应用开发
Nacos display service registration address error
Interviewer: what do you think is your biggest weakness?
Login page tablelayout
MySQL 02 初体验
LeetCode 刷题 第一天
TS study notes class
Infrared hyperspectral survey
Log4j epic loopholes, big companies like jd.com have been recruited
浴室带除雾化妆镜触摸芯片-DLT8T10S
Whole body multifunctional massage instrument chip-dltap602sd
USB充电式暖手宝芯片-DLTAP602SC-杰力科创
Use mobaxtermto establish a two-tier springboard connection
商品评论信息与评论信息分类