当前位置:网站首页>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
边栏推荐
- LeetCode 刷题 第一天
- Must the MySQL query column be consistent with the group by field?
- Whole body multifunctional massage instrument chip-dltap602sd
- LED带风扇护眼学习台灯触摸芯片-DLT8S12A
- 浴室带除雾化妆镜触摸芯片-DLT8T10S
- Run the uniapp to the mobile phone (real machine debugging)
- Hbuilder submission code
- 10 SQL optimization schemes summarized by Alibaba P8 (very practical)
- Wechat applet obtains openid, sessionkey, unionid
- 飞机大战英雄出场加子弹实现
猜你喜欢

Why don't you like it? It's easy to send mail in ci/cd

阿里架构师耗时280个小时整理的1015页分布式全栈小册,轻松入手分布式系统

音乐律动七彩渐变灯芯片--DLT8S04A-杰力科创

Redis注解

Join query and subquery

建木持续集成平台v2.5.2发布

Knowledge map - Jieba, pyhanlp, smoothnlp tools to realize Chinese word segmentation (part of speech)

微信支付及支付回调

How to realize the full-text content retrieval of word, PDF and txt files?

Led with fan eye protection learning table lamp touch chip-dlt8s12a
随机推荐
MySQL basic statement
EN 1155 building hardware swing door opener - CE certification
Quick access to website media resources
js中的函数与DOM获取元素和事件属性的使用
Uni app for wechat login (to be finished)
What if MySQL database forgets its password???
电动加热护颈枕芯片-DLTAP703SC
Aircraft collision detection
全自动吸奶器芯片-DLTAP703SD
JS tool - Cookie simple encapsulation
I'm stupid. When completable future is used with openfegin, it even reports an error
Solve the problem of JSP cascading
INSUFFICIENT_ ACCESS_ ON_ CROSS_ REFERENCE_ ENTITY APEX / SALESFORCE
Arrays and objects in JS
Interviewer: what do you think is your biggest weakness?
Login page tablelayout
百度地图鹰眼轨迹服务
全身多功能按摩仪芯片-DLTAP602SD
Electric heating neck pillow chip-dltap703sc
The song of the virtual idol was originally generated in this way!