网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
- * [♈ 定义](#__47)
* [♉ 自定义各种方法的行为的枚举](#__55)
* + [FileAccess 定义文件的读取、写入或读/写访问权限的常量](#FileAccess__63)
+ [FileShare 包含用于控制其他FileStream对象对同一文件可以具有的访问类型的常数](#FileShare_FileStream_75)
+ [FileMode 指定操作系统打开文件的方式](#FileMode__90)
* [♊ 常用方法](#__104)
* + [Copy(String, String, Boolean) 将现有文件复制到新文件。 允许覆盖同名的文件。](#CopyString_String_Boolean___106)
+ [Create(String) 在指定路径中创建或覆盖文件](#CreateString__196)
+ [Create(String, Int32, FileOptions) 创建或覆盖指定路径中的文件,指定缓冲区大小和一个描述如何创建或覆盖该文件的选项](#CreateString_Int32_FileOptions__261)
+ [Delete(String) 删除指定的文件](#DeleteString__324)
+ [Exists(String) 确定指定的文件是否存在](#ExistsString__400)
+ [GetCreationTime(String) 返回指定文件或目录的创建日期和时间](#GetCreationTimeString__429)
+ [Move(String, String) 将指定文件移到新位置,提供要指定新文件名的选项](#MoveString_String__492)
+ [Open(String, FileMode) 通过不共享的读/写访问权限打开指定路径上的 FileStream](#OpenString_FileMode__FileStream_561)
+ [Replace(String, String, String) 使用其他文件的内容替换指定文件的内容,这一过程将删除原始文件,并创建被替换文件的备份](#ReplaceString_String_String__624)
* [♋ 注解](#__697)
* [♌ 更多方法](#__709)
1️⃣ System.IO命名空间
.NET中的IO操作命名空间,包含允许读写文件和数据流的类型以及提供基本文件和目录支持的类型。
我们在.NET中的IO操作,经常需要调用一下几个类。
- FileStream类
文件流类,负责大文件的拷贝,读写。
- Path类
Path类中方法,基本都是对字符串(文件名)的操作,与实际文件没多大关系。
- File类
File类可以进行一些对小文件拷贝、剪切操作,还能读一些文档文件。
- Dirctory类
目录操作,创建文件、删除目录,获取目录下文件名等等。
2️⃣ File类
♈ 定义
提供用于创建、复制、删除、移动和打开单一文件的静态方法,并协助创建 FileStream 对象。
public static class File
♉ 自定义各种方法的行为的枚举
枚举 | 描述 |
---|---|
FileAccess | 指定对文件的读取和写入访问权限。 |
FileShare | 指定已在使用的文件所允许的访问级别。 |
FileMode | 指定是保留还是覆盖现有文件的内容,以及创建现有文件的请求是否会引发异常。 |
FileAccess 定义文件的读取、写入或读/写访问权限的常量
[System.Flags]
public enum FileAccess
Read | 1 | 对文件的读访问。 可从文件中读取数据。 与 Write 组合以进行读写访问。 |
---|---|---|
ReadWrite | 3 | 对文件的读写访问权限。 可从文件读取数据和将数据写入文件。 |
Write | 2 | 文件的写访问。 可将数据写入文件。 与 Read 组合以进行读写访问。 |
FileShare 包含用于控制其他FileStream对象对同一文件可以具有的访问类型的常数
[System.Flags]
public enum FileShare
Delete | 4 | 允许随后删除文件。 |
---|---|---|
Inheritable | 16 | 使文件句柄可由子进程继承。 Win32 不直接支持此功能。 |
None | 0 | 谢绝共享当前文件。 文件关闭前,打开该文件的任何请求(由此进程或另一进程发出的请求)都将失败。 |
Read | 1 | 允许随后打开文件读取。 如果未指定此标志,则文件关闭前,任何打开该文件以进行读取的请求(由此进程或另一进程发出的请求)都将失败。 但是,即使指定了此标志,仍可能需要附加权限才能够访问该文件。 |
ReadWrite | 3 | 允许随后打开文件读取或写入。 如果未指定此标志,则文件关闭前,任何打开该文件以进行读取或写入的请求(由此进程或另一进程发出)都将失败。 但是,即使指定了此标志,仍可能需要附加权限才能够访问该文件。 |
Write | 2 | 允许随后打开文件写入。 如果未指定此标志,则文件关闭前,任何打开该文件以进行写入的请求(由此进程或另一进过程发出的请求)都将失败。 但是,即使指定了此标志,仍可能需要附加权限才能够访问该文件。 |
FileMode 指定操作系统打开文件的方式
public enum FileMode
Append | 6 | 若存在文件,则打开该文件并查找到文件尾,或者创建一个新文件。 这需要 Append 权限。 FileMode.Append 只能与 FileAccess.Write 一起使用。 试图查找文件尾之前的位置时会引发 IOException 异常,并且任何试图读取的操作都会失败并引发 NotSupportedException 异常。 |
---|---|---|
Create | 2 | 指定操作系统应创建新文件。 如果此文件已存在,则会将其覆盖。 这需要 Write 权限。 FileMode.Create 等效于这样的请求:如果文件不存在,则使用 CreateNew;否则使用 Truncate。 如果该文件已存在但为隐藏文件,则将引发 UnauthorizedAccessException异常。 |
CreateNew | 1 | 指定操作系统应创建新文件。 这需要 Write 权限。 如果文件已存在,则将引发 IOException异常。 |
Open | 3 | 指定操作系统应打开现有文件。 打开文件的能力取决于 FileAccess 枚举所指定的值。 如果文件不存在,引发一个 FileNotFoundException 异常。 |
OpenOrCreate | 4 | 指定操作系统应打开文件(如果文件存在);否则,应创建新文件。 如果用 FileAccess.Read 打开文件,则需要 Read权限。 如果文件访问为 FileAccess.Write ,则需要 Write权限。 如果用 FileAccess.ReadWrite 打开文件,则同时需要 Read 和 Write权限。 |
Truncate | 5 | 指定操作系统应打开现有文件。 该文件被打开时,将被截断为零字节大小。 这需要 Write 权限。 尝试从使用 FileMode.Truncate 打开的文件中进行读取将导致 ArgumentException 异常。 |
♊ 常用方法
Copy(String, String, Boolean) 将现有文件复制到新文件。 允许覆盖同名的文件。
public static void Copy (string sourceFileName, string destFileName, bool overwrite);
参数
sourceFileName
string
要复制的文件。
destFileName
string
目标文件的名称。 它不能是一个目录或现有文件。
overwrite
bool
如果可以覆盖目标文件,则为
true
;否则为false
。
示例
以下示例将文件复制到 C:\archives\2008 备份文件夹。 它使用 方法的两个 Copy 重载,如下所示:
- 它首先使用 File.Copy(String, String) 方法重载来复制文本 (.txt) 文件。 代码演示此重载不允许覆盖已复制的文件。
- 然后,它 File.Copy(String, String, Boolean) 使用 方法重载将图片 (.jpg 文件) 。 该代码演示此重载允许覆盖已复制的文件。
string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
// Copy picture files.
foreach (string f in picList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
}
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
// Delete source files that were copied.
foreach (string f in txtList)
{
File.Delete(f);
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
Create(String) 在指定路径中创建或覆盖文件
public static System.IO.FileStream Create (string path);
参数
path
string
要创建的文件的路径及名称。
返回
一个 FileStream,它提供对
path
中指定的文件的读/写访问。
示例
以下示例在指定的路径中创建文件,将一些信息写入该文件,然后从该文件中读取。
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
try
{
// Create the file, or overwrite if the file exists.
using (FileStream fs = File.Create(path))
{
byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
// Open the stream and read it back.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
Create(String, Int32, FileOptions) 创建或覆盖指定路径中的文件,指定缓冲区大小和一个描述如何创建或覆盖该文件的选项
public static System.IO.FileStream Create (string path, int bufferSize, System.IO.FileOptions options);
参数
path
string
要创建的文件的路径及名称。
bufferSize
int
用于读取和写入到文件的已放入缓冲区的字节数。
options
FileOptions 值之一,它描述如何创建或覆盖该文件。
返回
具有指定缓冲区大小的新文件。
示例
以下示例演示如何在创建文件流时使用异步值。
using System;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace ConsoleApplication
{
class Program
{
static void Main(string[] args)
{
WriteToFile();
}
static async void WriteToFile()
{
byte[] bytesToWrite = Encoding.Unicode.GetBytes("example text to write");
using (FileStream createdFile = File.Create("c:/Temp/testfile.txt", 4096, FileOptions.Asynchronous))
{
await createdFile.WriteAsync(bytesToWrite, 0, bytesToWrite.Length);
}
}
}
}
Delete(String) 删除指定的文件
public static void Delete (string path);
参数
path
string
要删除的文件的名称。 不支持通配符。
示例
以下示例将文件组复制到 C:\archives\2008 备份文件夹,然后从源文件夹中将其删除。
string sourceDir = @"c:\current";
string backupDir = @"c:\archives\2008";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
// Copy picture files.
foreach (string f in picList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
}
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
// Delete source files that were copied.
foreach (string f in txtList)
{
File.Delete(f);
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
Exists(String) 确定指定的文件是否存在
public static bool Exists (string? path);
参数
path
string
文件或目录的路径。
返回
bool
如果
path
指向现有目录,则为true
;如果该目录不存在或者在尝试确定指定目录是否存在时出错,则为false
。
示例
下面的示例确定文件是否存在。
string curFile = @"c:\temp\test.txt";
Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist.");
GetCreationTime(String) 返回指定文件或目录的创建日期和时间
public static DateTime GetCreationTime (string path);
参数
path
string
目录的路径。
返回
一个设置为指定目录的创建日期和时间的结构。 该值用本地时间表示。
示例
下面的示例演示了 GetCreationTime
。
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!
static DateTime GetCreationTime (string path);
**参数**
>
> `path`
>
>
> **string**
>
>
> 目录的路径。
>
>
>
**返回**
>
> [DateTime](https://bbs.csdn.net/topics/618545628)
>
>
> 一个设置为指定目录的创建日期和时间的结构。 该值用本地时间表示。
>
>
>
**示例**
下面的示例演示了 `GetCreationTime` 。
[外链图片转存中...(img-fh08m5QV-1715635324299)]
[外链图片转存中...(img-zydqLJXa-1715635324299)]
**网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**
**[需要这份系统化资料的朋友,可以戳这里获取](https://bbs.csdn.net/topics/618545628)**
**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**