Maison  >  Article  >  développement back-end  >  Informations sur le fichier C#

Informations sur le fichier C#

WBOY
WBOYoriginal
2024-09-03 15:23:39266parcourir

Pour travailler avec des fichiers dans le framework .NET, l'espace de noms important utilisé est l'espace de noms system.IO et de même, nous avons une classe appelée classe FileInfo en C# qui ne consiste pas en méthodes statiques et seuls les objets instanciés peuvent utiliser cette classe, un Un fichier sur un disque ou un emplacement d'un réseau est représenté par l'objet fileinfo, les objets filestream peuvent être créés à l'aide d'objets fileinfo et des méthodes d'instance sont fournies par la classe fileinfo pour créer, supprimer, copier, déplacer et ouvrir les fichiers et nous pouvons avoir plus de contrôle sur les opérations de lecture et d'écriture sur les fichiers pour écrire manuellement le code qui peut être lu ou des octets peuvent être écrits à partir d'un fichier en utilisant la classe fileinfo.

La syntaxe de la classe C# FileInfo est la suivante :

[SerializableAttribute]
[ComVisibleAttribute(true)]
public sealed class FileInfo : FileSystemInfo

Fonctionnement de la classe C# FileInfo

Pour comprendre le fonctionnement de la classe FileInfo en C#, nous devons comprendre les constructeurs de la classe FileInfo, les propriétés de la classe FileInfo et les méthodes de la classe FileInfo.

Les constructeurs de la classe FileInfo sont expliqués comme ci-dessous :

  • FileInfo(string) : Une nouvelle instance de la classe FileInfo est initialisée et elle agit comme un wrapper pour le chemin du fichier.

Il existe plusieurs propriétés de la classe FileInfo. Ils s'expliquent ainsi :

  • Attributs : Nous pouvons obtenir ou définir les attributs du fichier actuel ou du répertoire actuel à l'aide de la propriété Attributes.
  • CreationTime : Nous pouvons obtenir ou définir l'heure de création du fichier actuel ou du répertoire actuel à l'aide de la propriété Creation Time.
  • Répertoire : Nous pouvons obtenir une instance du répertoire parent en utilisant la propriété Directory.
  • DirectoryName : Nous pouvons obtenir une chaîne qui représente le chemin complet du répertoire en utilisant la propriété Directory Name.
  • Exists : Nous pouvons obtenir une valeur qui indique si un fichier existe ou non en utilisant la propriété Exists.
  • FullName : Nous pouvons obtenir le chemin complet du répertoire ou le chemin complet du fichier en utilisant la propriété Full Name.
  • IsReadOnly : Nous pouvons obtenir ou définir une valeur qui peut déterminer si le fichier actuel a une propriété en lecture seule en utilisant la propriété Is Read Only.
  • LastAccessTime : Nous pouvons obtenir ou définir l'heure à laquelle le fichier actuel ou le répertoire actuel a été consulté pour la dernière fois en utilisant la propriété Heure du dernier accès.
  • Longueur : Nous pouvons obtenir la taille du fichier actuel en octets en utilisant la propriété length.
  • Nom : Nous pouvons obtenir le nom du fichier en utilisant la propriété name.

Il existe plusieurs méthodes de classe FileInfo. Ils s'expliquent ainsi :

  • AppendText(): A stream writer is created using this method AppendText(). The text is appended to the file which is represented by the instance of the FileInfo class by using this stream writer.
  • CopyTo(String): An existing file can be copied to a new file using this method CopyTo(String).
  • Create(): A file can be created using this method Create().
  • CreateText(): A stream writer is created using this method CreateText()  and this stream writer writes to a new text file.
  • Decrypt(): A file can be decrypted using this method decrypt() which was originally encrypted by using the encrypt method by the current account.
  • Delete(): A file can be deleted permanently using the Delete() method.
  • Encrypt(): A file can be encrypted using Encrypt() method and this file can be decrypted by using Decrypt() method provided the account used for encryption is the same account used for decryption also.
  • GetAccessControl(): A file security object is obtained using this method GetAccessControl()  and it encapsulates the entries of the Access Control List (ACL).
  • MoveTo(String): A specified file can be moved from one location to a newly specified location using MoveTo(String) method.
  • Open(File Mode): A file can be opened in a specified mode using the Open(File Mode) method.
  • OpenRead(): A file stream that can be read-only can be created using the OpenRead() method.
  • OpenText(): A stream reader can be created using this method OpenText() which can read from an existing file with UTF8 encoding.
  • OpenWrite(): A file stream that can be written only can be created using this method OpenWrite().
  • Refresh(): The state of the object can be refreshed using this method Refresh().
  • Replace(String, String): The contents of a specified file can be replaced by the contents of the other file which is described by the current object of the FileInfo class using this method Replace(String, String).
  • ToString(): The path is returned as a string using this method ToString().

As we have understood the constructors of FileInfo class, Properties of FileInfo class and methods of the FileInfo class, now consider the below program:

Code:

using System;
using System.IO;
namespace Program
{
class Check
{
static void Main(string[] args)
{
try
{
// the file location is specified where the file is to be created
string location = "C:\Users\shivakumarsh\Desktop\new.txt";
// instance of the fileinfo class is created
FileInfo file = new FileInfo(location);
// an empty file is created
file.Create();
Console.WriteLine("Creation of file is successfull");
}
catch(IOException e)
{
Console.WriteLine("Failed attempt to create file "+e);
}
}
}
}

Output:

Informations sur le fichier C#

In the above program, a namespace called the program is declared. Then the main method consisting of the try-catch block is defined. The try block consists of the location string where the new file needs to be created. An instance of the file info class is created, and the location string is passed as a parameter to the instance of the file info class. Create () method is invoked on the object of the file info class to create a new file in the location specified by the location string. If the file creation is successful, the success message is printed otherwise an exception is raised which is included in the catch block.

Example of C# FileInfo

C# program to demonstrate usage of File Info class.

Code:

using System;
using System.IO;
namespace Program
{
class Check
{
static void Main(string[] args)
{
// the file location is specified where the file is to be located
string location = "C:\Users\shivakumarsh\Desktop\new.txt";
// instance of the fileinfo class is created
FileInfo file = new FileInfo(location);
// The specified file is deleted
file.Delete();
Console.WriteLine("Deletion of file is successfull");
}
}
}

Output:

Informations sur le fichier C#

Conclusion

In this tutorial, we understand the concept of FileInfo class in C# through definition, constructors of FileInfo class, properties of FileInfo class, methods of FileInfo class, working of FileInfo class through examples.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn
Article précédent:C# StreamWriterArticle suivant:C# StreamWriter