🐋作者简介:博主是一位.Net开发者,同时也是RPA和低代码平台的践行者。
🦀专栏简介:博主针对.Net开发和C站问答过程中遇到的问题进行总结,形成本专栏,希望可以帮助到您解决问题。
🐶座右铭:总有一天你所坚持的会反过来拥抱你。
🌈写在前面:本文主要介绍System.IO命名空间的FileInfo 类,介绍其常用的方法和示例说明。
👉本文关键字:System.IO、FileInfo类、文件信息、方法示例、C#
1️⃣ System.IO命名空间
.NET中的IO操作命名空间,包含允许读写文件和数据流的类型以及提供基本文件和目录支持的类型。
我们在.NET中的IO操作,经常需要调用一下几个类。
- FileStream类
文件流类,负责大文件的拷贝,读写。
- Path类
Path类中方法,基本都是对字符串(文件名)的操作,与实际文件没多大关系。
- File类
File类可以进行一些对小文件拷贝、剪切操作,还能读一些文档文件。
- Dirctory类
目录操作,创建文件、删除目录,获取目录下文件名等等。
2️⃣ FileInfo类
♈ 定义
提供用于创建、复制、删除、移动和打开文件的属性和实例方法,并且帮助创建 FileStream 对象。 此类不能被继承。
public sealed class FileInfo : System.IO.FileSystemInfo
♉ 构造函数
FileInfo(String) 初始化作为文件路径的包装的 FileInfo 类的新实例
public FileInfo (string fileName);
参数
fileName
string
新文件的完全限定名或相对文件名。 路径不要以目录分隔符结尾。
示例
以下示例使用此构造函数创建两个文件,然后写入、读取、复制和删除。
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
FileInfo fi1 = new FileInfo(path);
if (!fi1.Exists)
{
//Create a file to write to.
using (StreamWriter sw = fi1.CreateText())
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
//Open the file to read from.
using (StreamReader sr = fi1.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
try
{
string path2 = path + "temp";
FileInfo fi2 = new FileInfo(path2);
//Ensure that the target does not exist.
fi2.Delete();
//Copy the file.
fi1.CopyTo(path2);
Console.WriteLine("{0} was copied to {1}.", path, path2);
//Delete the newly created file.
fi2.Delete();
Console.WriteLine("{0} was successfully deleted.", path2);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//Hello
//And
//Welcome
//c:\MyTest.txt was copied to c:\MyTest.txttemp.
//c:\MyTest.txttemp was successfully deleted.
以下示例打开现有文件或创建文件,将文本追加到文件,并显示结果。
using System;
using System.IO;
public class FileInfoMainTest
{
public static void Main()
{
// Open an existing file, or create a new one.
FileInfo fi = new FileInfo("temp.txt");
// Create a writer, ready to add entries to the file.
StreamWriter sw = fi.AppendText();
sw.WriteLine("This is a new entry to add to the file");
sw.WriteLine("This is yet another line to add...");
sw.Flush();
sw.Close();
// Get the information out of the file and display it.
StreamReader sr = new StreamReader( fi.OpenRead() );
while (sr.Peek() != -1)
Console.WriteLine( sr.ReadLine() );
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//Add as many lines as you like...
//Add another line to the output...
//This is a new entry to add to the file
//This is yet another line to add...
♊ 字段
表示目录或文件的完全限定目录
protected string FullPath;
♋ 属性
CreationTime 获取或设置当前文件或目录的创建时间
public DateTime CreationTime { get; set; }
Directory 获取父目录的实例
public System.IO.DirectoryInfo? Directory { get; }
DirectoryName 获取表示目录的完整路径的字符串
public string? DirectoryName { get; }
Exists 获取指示目录是否存在的值
public abstract bool Exists { get; }
Extension 获取文件名的扩展名部分,包括前导点即使它是整个文件名,或者不存在扩展名的空字符串
public string Extension { get; }
FullName 获取目录或文件的完整目录
public virtual string FullName { get; }
Name 获取此 DirectoryInfo 实例的名称
public override string Name { get; }
Name此属性仅返回目录的名称,例如"Bin"。 若要获取完整路径,例如"c:\public\Bin",请使用 FullName 属性。
Length 获取当前文件的大小(以字节为单位)
public long Length { get; }
示例
以下示例显示指定文件的大小
// The following example displays the names and sizes
// of the files in the specified directory.
using System;
using System.IO;
public class FileLength
{
public static void Main()
{
// Make a reference to a directory.
DirectoryInfo di = new DirectoryInfo("c:\\");
// Get a reference to each file in that directory.
FileInfo[] fiArr = di.GetFiles();
// Display the names and sizes of the files.
Console.WriteLine("The directory {0} contains the following files:", di.Name);
foreach (FileInfo f in fiArr)
Console.WriteLine("The size of {0} is {1} bytes.", f.Name, f.Length);
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//The directory c:\ contains the following files:
//The size of MyComputer.log is 274 bytes.
//The size of AUTOEXEC.BAT is 0 bytes.
//The size of boot.ini is 211 bytes.
//The size of CONFIG.SYS is 0 bytes.
//The size of hiberfil.sys is 1072775168 bytes.
//The size of IO.SYS is 0 bytes.
//The size of MASK.txt is 2700 bytes.
//The size of mfc80.dll is 1093632 bytes.
//The size of mfc80u.dll is 1079808 bytes.
//The size of MSDOS.SYS is 0 bytes.
//The size of NTDETECT.COM is 47564 bytes.
//The size of ntldr is 250032 bytes.
//The size of pagefile.sys is 1610612736 bytes.
//The size of UpdatePatch.log is 22778 bytes.
//The size of UpdatePatch.txt is 30 bytes.
//The size of wt3d.ini is 234 bytes.
♌ 常用方法
AppendText() 创建一个 StreamWriter,它向 FileInfo 的此实例表示的文件追加文本
public System.IO.StreamWriter AppendText ();
返回
StreamWriter在
path
中指定的最后一个目录。
示例
以下示例将文本追加到文件中,并从文件中读取。
using System;
using System.IO;
class Test
{
public static void Main()
{
FileInfo fi = new FileInfo(@"c:\MyTest.txt");
// This text is added only once to the file.
if (!fi.Exists)
{
//Create a file to write to.
using (StreamWriter sw = fi.CreateText())
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// This text will always be added, making the file longer over time
// if it is not deleted.
using (StreamWriter sw = fi.AppendText())
{
sw.WriteLine("This");
sw.WriteLine("is Extra");
sw.WriteLine("Text");
}
//Open the file to read from.
using (StreamReader sr = fi.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//Hello
//And
//Welcome
//This
//is Extra
//Text
//When you run this application a second time, you will see the following output:
//
//Hello
//And
//Welcome
//This
//is Extra
//Text
//This
//is Extra
//Text
以下示例演示如何将文本追加到文件末尾,并显示追加操作的结果。 首次调用此例程时,如果该文件不存在,则会创建该文件。 之后,指定的文本将追加到文件。
using System;
using System.IO;
public class AppendTextTest
{
public static void Main()
{
FileInfo fi = new FileInfo("temp.txt");
// Create a writer, ready to add entries to the file.
StreamWriter sw = fi.AppendText();
sw.WriteLine("Add as many lines as you like...");
sw.WriteLine("Add another line to the output...");
sw.Flush();
sw.Close();
// Get the information out of the file and display it.
// Remember that the file might have other lines if it already existed.
StreamReader sr = new StreamReader(fi.OpenRead());
while (sr.Peek() != -1)
Console.WriteLine( sr.ReadLine() );
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//Add as many lines as you like...
//Add another line to the output...
Copy(String, Boolean) 将现有文件复制到新文件,允许覆盖现有文件
public System.IO.FileInfo CopyTo (string destFileName, bool overwrite);
参数
destFileName
string
要复制到的新文件的名称。
overwrite
bool
如果可以覆盖目标文件,则为
true
;否则为false
。
返回
FileInfo为新文件;如果
overwrite
是true
,则为现有文件的覆盖。 如果文件存在且overwrite
为false
,则引发 IOException。
示例
以下示例演示了方法的两个 CopyTo
重载。
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\SoureFile.txt";
string path2 = @"c:\NewFile.txt";
FileInfo fi1 = new FileInfo(path);
FileInfo fi2 = new FileInfo(path2);
try
{
// Create the source file.
using (FileStream fs = fi1.Create()) { }
//Ensure that the target file does not exist.
if (File.Exists(path2))
{
fi2.Delete();
}
//Copy the file.f
fi1.CopyTo(path2);
Console.WriteLine("{0} was copied to {1}.", path, path2);
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
}
}
以下示例演示如何将一个文件复制到另一个文件,指定是否覆盖已存在的文件。
using System;
using System.IO;
public class CopyToTest
{
public static void Main()
{
// Create a reference to a file, which might or might not exist.
// If it does not exist, it is not yet created.
FileInfo fi = new FileInfo("temp.txt");
// Create a writer, ready to add entries to the file.
StreamWriter sw = fi.AppendText();
sw.WriteLine("Add as many lines as you like...");
sw.WriteLine("Add another line to the output...");
sw.Flush();
sw.Close();
// Get the information out of the file and display it.
StreamReader sr = new StreamReader( fi.OpenRead() );
Console.WriteLine("This is the information in the first file:");
while (sr.Peek() != -1)
Console.WriteLine( sr.ReadLine() );
// Copy this file to another file. The true parameter specifies
// that the file will be overwritten if it already exists.
FileInfo newfi = fi.CopyTo("newTemp.txt", true);
// Get the information out of the new file and display it.
sr = new StreamReader( newfi.OpenRead() );
Console.WriteLine("{0}This is the information in the second file:", Environment.NewLine);
while (sr.Peek() != -1)
Console.WriteLine( sr.ReadLine() );
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is the information in the first file:
//Add as many lines as you like...
//Add another line to the output...
//Add as many lines as you like...
//Add another line to the output...
//This is the information in the second file:
//Add as many lines as you like...
//Add another line to the output...
//Add as many lines as you like...
//Add another line to the output...
Create() 创建文件
public System.IO.FileStream Create ();
返回
FileStream新文件。
示例
以下示例创建对文件的引用,然后使用该文件在磁盘 FileInfo.Create()
上创建该文件。
using System;
using System.IO;
public class DeleteTest
{
public static void Main()
{
// Create a reference to a file.
FileInfo fi = new FileInfo("temp.txt");
// Actually create the file.
FileStream fs = fi.Create();
// Modify the file as required, and then close the file.
fs.Close();
// Delete the file.
fi.Delete();
}
}
以下示例创建一个文件,向该文件添加一些文本,并从该文件中读取。
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\MyTest.txt";
FileInfo fi = new FileInfo(path);
// Delete the file if it exists.
if (fi.Exists)
{
fi.Delete();
}
//Create the file.
using (FileStream fs = fi.Create())
{
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 = fi.OpenText())
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//This is some text in the file.
Delete() 永久删除文件
public override void Delete ();
示例
下面的示例演示 Delete
方法
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\MyTest.txt";
FileInfo fi1 = new FileInfo(path);
try
{
using (StreamWriter sw = fi1.CreateText()) {}
string path2 = path + "temp";
FileInfo fi2 = new FileInfo(path2);
//Ensure that the target does not exist.
fi2.Delete();
//Copy the file.
fi1.CopyTo(path2);
Console.WriteLine("{0} was copied to {1}.", path, path2);
//Delete the newly created file.
fi2.Delete();
Console.WriteLine("{0} was successfully deleted.", path2);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
//c:\MyTest.txt was copied to c:\MyTest.txttemp.
//c:\MyTest.txttemp was successfully deleted.
以下示例创建、关闭和删除文件。
using System;
using System.IO;
public class DeleteTest
{
public static void Main()
{
// Create a reference to a file.
FileInfo fi = new FileInfo("temp.txt");
// Actually create the file.
FileStream fs = fi.Create();
// Modify the file as required, and then close the file.
fs.Close();
// Delete the file.
fi.Delete();
}
}
MoveTo(String) 将指定文件移到新位置,提供要指定新文件名的选项
public void MoveTo (string destFileName);
参数
destFileName
string
要将文件移动到的路径,可以指定不同的文件名。
示例
以下示例演示如何将文件移动到其他位置并重命名该文件。
using System;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.IO;
using System.Reflection;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
namespace Microsoft.Samples.MoveTo.CS
{
class Program
{
private static string sourcePath = Environment.GetFolderPath
(Environment.SpecialFolder.MyDocuments) +
@"\FileInfoTestDirectory\MoveFrom\FromFile.xml";
private static string destPath = Environment.GetFolderPath
(Environment.SpecialFolder.MyDocuments) +
@"\FileInfoTestDirectory\DestFile.xml";
//
// The main entry point for the application.
//
[STAThread()] static void Main ()
{
// Change Console properties to make it obvious that
// the application is starting.
Console.Clear();
// Move it to the upper left corner of the screen.
Console.SetWindowPosition(0, 0);
// Make it very large.
Console.SetWindowSize(Console.LargestWindowWidth - 24,
Console.LargestWindowHeight - 16);
Console.WriteLine("Welcome.");
Console.WriteLine("This application demonstrates the FileInfo.MoveTo method.");
Console.WriteLine("Press any key to start.");
string s = Console.ReadLine();
Console.Write(" Checking whether ");
Console.Write(sourcePath);
Console.WriteLine(" exists.");
FileInfo fInfo = new FileInfo (sourcePath);
EnsureSourceFileExists();
DisplayFileProperties(fInfo);
Console.WriteLine("Preparing to move the file to ");
Console.Write(destPath);
Console.WriteLine(".");
MoveFile(fInfo);
DisplayFileProperties(fInfo);
Console.WriteLine("Preparing to delete directories.");
DeleteFiles();
Console.WriteLine("Press the ENTER key to close this application.");
s = Console.ReadLine();
}
//
// Moves the supplied FileInfo instance to destPath.
//
private static void MoveFile(FileInfo fInfo)
{
try
{
fInfo.MoveTo(destPath);
Console.WriteLine("File moved to ");
Console.WriteLine(destPath);
} catch (Exception ex) {
DisplayException(ex);
}
}
//
// Ensures that the test directories
// and the file FromFile.xml all exist.
//
private static void EnsureSourceFileExists()
{
FileInfo fInfo = new FileInfo(sourcePath);
string dirPath = fInfo.Directory.FullName;
if (!Directory.Exists(dirPath))
{
Directory.CreateDirectory(dirPath);
}
if (File.Exists(destPath))
{
File.Delete(destPath);
}
Console.Write("Creating file ");
Console.Write(fInfo.FullName);
Console.WriteLine(".");
try
{
if (!fInfo.Exists)
{
Console.WriteLine("Adding data to the file.");
WriteFileContent(10);
Console.WriteLine("Successfully created the file.");
}
}
catch (Exception ex)
{
DisplayException(ex);
}
finally
{
dirPath = null;
}
}
//
// Creates and saves an Xml file to sourcePath.
//
private static void WriteFileContent(int totalElements)
{
XmlDocument doc = new XmlDocument();
doc.PreserveWhitespace = true;
doc.AppendChild(doc.CreateXmlDeclaration("1.0", null, "yes"));
doc.AppendChild(doc.CreateWhitespace("\r\n"));
XmlElement root = doc.CreateElement("FileInfo.MoveTo");
root.AppendChild(doc.CreateWhitespace("\r\n"));
int index = 0;
XmlElement elem;
while (index < totalElements)
{
elem = doc.CreateElement("MyElement");
elem.SetAttribute("Index", index.ToString());
elem.AppendChild(doc.CreateWhitespace("\r\n"));
elem.AppendChild(doc.CreateTextNode(String.Format
("MyElement at position {0}.", index)));
elem.AppendChild(doc.CreateWhitespace("\r\n"));
root.AppendChild(elem);
root.AppendChild(doc.CreateWhitespace("\r\n"));
index++;
}
doc.AppendChild(root);
doc.AppendChild(doc.CreateWhitespace("\r\n"));
doc.Save(sourcePath);
elem = null;
root = null;
doc = null;
}
//
// Displays FullName, CreationTime, and LastWriteTime of the supplied
// FileInfo instance, then displays the text of the file.
//
private static void DisplayFileProperties(FileInfo fInfo)
{
Console.WriteLine("The FileInfo instance shows these property values.");
StreamReader reader = null;
try
{
Console.Write("FullName: ");
Console.WriteLine(fInfo.FullName);
Console.Write("CreationTime: ");
Console.WriteLine(fInfo.CreationTime);
Console.Write("LastWriteTime: ");
Console.WriteLine(fInfo.LastWriteTime);
Console.WriteLine();
Console.WriteLine("File contents:");
Console.WriteLine();
reader = new StreamReader(fInfo.FullName);
while (!reader.EndOfStream)
{
Console.WriteLine(reader.ReadLine());
}
Console.WriteLine();
}
catch (Exception ex)
{
DisplayException(ex);
}
finally
{
if (reader != null)
{
reader.Close();
}
reader = null;
}
}
//
// Deletes the test directory and all its files and subdirectories.
//
private static void DeleteFiles()
{
try
{
DirectoryInfo dInfo = new DirectoryInfo(Environment.GetFolderPath
(Environment.SpecialFolder.MyDocuments) + "\\FileInfoTestDirectory");
if (dInfo.Exists)
{
dInfo.Delete(true);
Console.WriteLine("Successfully deleted directories and files.");
}
dInfo = null;
}
catch (Exception ex)
{
DisplayException(ex);
}
}
//
// Displays information about the supplied Exception. This
// code is not suitable for production applications.
//
private static void DisplayException(Exception ex)
{
StringBuilder sb = new StringBuilder();
sb.Append("An exception of type \"");
sb.Append(ex.GetType().FullName);
sb.Append("\" has occurred.\r\n");
sb.Append(ex.Message);
sb.Append("\r\nStack trace information:\r\n");
MatchCollection matchCol = Regex.Matches(ex.StackTrace,
@"(at\s)(.+)(\.)([^\.]*)(\()([^\)]*)(\))((\sin\s)(.+)(:line )([\d]*))?");
int L = matchCol.Count;
string[] argList;
Match matchObj;
int y, K;
for(int x = 0; x < L; x++)
{
matchObj = matchCol[x];
sb.Append(matchObj.Result("\r\n\r\n$1 $2$3$4$5"));
argList = matchObj.Groups[6].Value.Split(new char[] { ',' });
K = argList.Length;
for (y = 0; y < K; y++)
{
sb.Append("\r\n ");
sb.Append(argList[y].Trim().Replace(" ", " "));
sb.Append(',');
}
sb.Remove(sb.Length - 1, 1);
sb.Append("\r\n)");
if (0 < matchObj.Groups[8].Length)
{
sb.Append(matchObj.Result("\r\n$10\r\nline $12"));
}
}
argList = null;
matchObj = null;
matchCol = null;
Console.WriteLine(sb.ToString());
sb = null;
}
}
}
//This code produces output similar to the following;
//results may vary based on the computer/file structure/etc.:
//
// Welcome.
// This application demonstrates the FileInfo.MoveTo method.
// Press any key to start.
//
// Checking whether C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml exists.
// Creating file C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml.
// Adding data to the file.
// Successfully created the file.
// The FileInfo instance shows these property values.
// FullName: C:\Documents and Settings\MyComputer\My Documents\FileInfoTestDirectory\MoveFrom\FromFile.xml
// CreationTime: 4/18/2006 1:24:19 PM
// LastWriteTime: 4/18/2006 1:24:19 PM
//
// File contents:
//
// <?xml version="1.0" standalone="yes"?>
// <MyElement Index="0">
// MyElement at position 0.
// <MyElement Index="1">
// MyElement at position 1.
// <MyElement Index="2">
// MyElement at position 2.
// <MyElement Index="3">
// MyElement at position 3.
// <MyElement Index="4">
// MyElement at position 4.
// <MyElement Index="5">
// MyElement at position 5.
// <MyElement Index="6">
// MyElement at position 6.
// <MyElement Index="7">
// MyElement at position 7.
// <MyElement Index="8">
// MyElement at position 8.
// <MyElement Index="9">
// MyElement at position 9.
// Preparing to move the file to
// C:\Documents and Settings\MYComputer\My Documents\FileInfoTestDirectory\DestFile.xml.
// File moved to
// C:\Documents and Settings\MYComputer\My Documents\FileInfoTestDirectory\DestFile.xml
// The FileInfo instance shows these property values.
// FullName: C:\Documents and Settings\MYComputer\My Documents\FileInfoTestDirectory\DestFile.xml
// CreationTime: 4/18/2006 1:24:19 PM
// LastWriteTime: 4/18/2006 1:24:19 PM
//
// File contents:
//
// <?xml version="1.0" standalone="yes"?>
// <MyElement Index="0">
// MyElement at position 0.
// <MyElement Index="1">
// MyElement at position 1.
// <MyElement Index="2">
// MyElement at position 2.
// <MyElement Index="3">
// MyElement at position 3.
// <MyElement Index="4">
// MyElement at position 4.
// <MyElement Index="5">
// MyElement at position 5.
// <MyElement Index="6">
// MyElement at position 6.
// <MyElement Index="7">
// MyElement at position 7.
// <MyElement Index="8">
// MyElement at position 8.
// <MyElement Index="9">
// MyElement at position 9.
//
// Preparing to delete directories.
// Successfully deleted directories and files.
// Press the ENTER key to close this application.
♍ 注解
将 FileInfo 类用于典型的操作,例如复制、移动、重命名、创建、打开、删除和追加到文件。
如果要对同一文件执行多个操作,则使用 FileInfo 实例方法(而不是类的相应静态方法 File )可能更高效,因为安全检查并不总是必要的。
创建或打开文件时, FileInfo 许多方法都会返回其他 I/O 类型。 可以使用这些其他类型的进一步操作文件。 有关详细信息,请参阅特定FileInfo成员,例如Open、、OpenReadOpenText、CreateText或Create。
♎ 更多方法
更多方法请查阅官方文档 FileInfo 。
⭐写在结尾:文章中出现的任何错误请大家批评指出,一定及时修改。
希望写在这里的小伙伴能给个三连支持!