FileInfo Class and File Class
The File object is a class that provides high-level functions to make copying, moving, deleting, and opening files easier. In addition, it provides some methods to aid in the creation of FileStrea
The File object is a class that provides high-level functions to make copying, moving, deleting, and opening files easier. In addition, it provides some methods to aid in the creation of FileStreams. To make single calls easier, all the methods provided in the File class are static. The following Example demonstrates some of the features available in the File class and shows how to create a file using the File class.
using System;
using System.IO;
namespace SAMS.VisualCSharpUnleashed.Chapter7
{
class FileExample
{
[STAThread]
static void Main(string[] args)
{
// Create a new file
string filePath = @"test.txt";
// Delete the file if it already exists
if(File.Exists(filePath))
File.Delete(filePath);
// Create the file
File.Create(filePath);
System.Console.WriteLine("The file was created.");
System.Console.ReadLine();
}
}
}
The FileInfo object is another class that provides high-level functions to make copying, moving, deleting, and opening files easier. In addition, it provides some methods to aid in the creation of streams. Unlike the File class, the FileInfo class is made up entirely of instance methods. The following Example demonstrates how to use the FileInfo class to list information about a particular file.
using System;
using System.IO;
namespace SAMS.VisualCSharpUnleashed.Chapter7
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
// Create a new file
string filePath = @"c:/test.txt";
FileInfo fi = new FileInfo(filePath);
// Print out the information if the file exists
if(fi.Exists)
{
System.Console.WriteLine(
"The file: {0} was last accessed on {1} " +
" and contains {2} bytes of data.", filePath,
fi.LastAccessTime, fi.Length);
}
else
System.Console.WriteLine("The file: {0} does not exist.", filePath);
System.Console.ReadLine();
}
}
}
Security checks are made on each call of the static methods in the File class. Because the FileInfo class is an instance class, the security checks need to be performed only once. A general rule of thumb to use when deciding which class to use is this: If you are performing a single operation on a file, the File class might be the right choice. If, however, you are performing multiple operations on a file, the FileInfo class is probably the most efficient choice.

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。
更多推荐
所有评论(0)