1. 程式人生 > >c#管理文件系統

c#管理文件系統

args names and 返回 ota 位置 med folder seve

using System;
using System.Collections.Generic;
using System.IO;
using static System.Console;

/*System.IO:
       FileSystemInfo       DriveInfo
        |         |
DirectoryInfo   FileInfo    

    Directory   File        Path

Directory和File類只含靜態方法,不能被實例化(多用於執行一個操作)
DirectoryInfo和FileInfo提供與Directory和File大致相同的公共方法
    (多用於對同一個對象執行多個操作)

DriveInfo檢查驅動器信息(磁盤C,D,E...)
*/ namespace ConsoleApp { class Program { static void Main(string[] args) { //PrintDrivesInfo(); //Path類 string path = Path.Combine(@"D:\Projects", "ReadMe.txt"); WriteLine(path); path = GetDocumentsFolder(); WriteLine(path);
//Environment.SpecialFolder枚舉了桌面、音樂、圖片等 //創建文件, 路徑必須存在 string fileName = "D:\\Sample1.txt"; File.WriteAllText(fileName, "Hello World!"); //復制文件 執行時間略長 var file = new FileInfo(@".\ReadMe.txt"); //路徑需存在,不能覆蓋現有文件 if (file.Exists && !File.Exists(@"
C:\ReadMe.txt")) file.CopyTo(@"C:\ReadMe.txt"); // File.Copy(@"C:\ReadMe.txt", @"C:\Copies\ReadMe.txt"); //刪除、移動 文件或文件夾 //File.Delete(path); //File.Move(path, path); string[] lines = File.ReadAllLines(fileName); //在讀取完整個文件之前就可遍歷它 IEnumerable<string> lines1 = File.ReadAllLines(fileName); foreach (var line in lines1) { } string[] movies = { "Snow White And The Seven Dwarfs", "Gone With The Wind" }; File.WriteAllLines(fileName, movies); //追加 File.AppendAllLines(fileName, movies); //枚舉文件 Directory.GetFiles(path); //返回目錄中所有文件的名稱(包括其路徑) Directory.GetDirectories(path);//返回目錄中子目錄的名稱(包括其路徑) //同上,但它們使用IEnumerable<string>立即開始返回結果 Directory.EnumerateFiles(path); Directory.EnumerateDirectories(path); } public static void PrintDrivesInfo() { DriveInfo[] drives = DriveInfo.GetDrives(); foreach (var drive in drives) { if (drive.IsReady) { WriteLine($"Drive name: {drive.Name}"); //C:\ WriteLine($"Format: {drive.DriveFormat}"); //NTFS WriteLine($"Type: {drive.DriveType}"); //Fixed WriteLine($"Root directory: {drive.RootDirectory}"); //C:\ WriteLine($"Volume label: {drive.VolumeLabel}"); //System WriteLine($"Free space: {drive.TotalFreeSpace}"); //... WriteLine($"Available space: {drive.AvailableFreeSpace}"); WriteLine($"Total size: {drive.TotalSize}"); WriteLine(); } } } private static string GetDocumentsFolder() { #if NET46 return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); #else string drive = Environment.GetEnvironmentVariable("HOMEDRIVE"); string path = Environment.GetEnvironmentVariable("HOMEPATH"); //return Path.Combine(drive+path, "documents");//不一定正確,有可能用戶改變了文檔的位置 return Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); #endif } } }

c#管理文件系統