|
// test si un fichier existe
if (File.Exists(@"C:\Dossier\fichier.txt"))
// test si un nom de fichier est valide
if (String.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
// lire le contenu d'un fichier en mémoire
string content = File.ReadllText(@"C:\Dossier\fichier.txt");
// WriteAllText creates a file, writes the specified string to the file, and then closes the file.
File.WriteAllText(@"C:\Dossier\fichier.txt", "Texte à écrire");
// Create a string array that consists of three lines.
string[] lines = { "First line", "Second line", "Third line" };
// WriteAllLines creates a file, writes a collection of strings to the file, and then closes the file.
File.WriteAllLines(@"C:\Dossier\fichier.txt", lines);
// renommer un fichier. La destination doit être un fichier.
File.Move(@"C:\Dossier\fichier.txt", @"C:\Dossier\fichier2.txt");
// copier un fichier. La destination doit être un fichier.
File.Copy(@"C:\Dossier\fichier.txt", @"C:\Dossier\fichier2.txt");
// If the file to be deleted does not exist, no exception is thrown.
File.Delete(@"C:\Dossier\fichier.txt");
|
Directory
|
// créer toute l'arborescence
Directory.CreateDirectory("C:\dossier\sous-dossier");
IEnumerable<string> folderPaths = Directory.EnumerateDirectories("/chemin/vers/un/dossier", "*.txt", SearchOption.AllDirectories);
// search pattern: par défaut "*", ne prend pas en charge les regex
// * -> 0 ou plusieurs caractères
// ? -> 1 caractère
// enumeration option: par défaut SearchOption.TopDirectoryOnly
string[] folderPaths = Directory.GetDirectories("/chemin/vers/un/dossier", "*", SearchOption.AllDirectories);
string[] filePaths = Directory.GetFiles("/chemin/vers/un/dossier", "*.txt", SearchOption.AllDirectories);
// pour exclure les liens symboliques
string[] folderPaths = new DirectoryInfo("/chemin/vers/un/dossier").GetDirectories()
.Where(di => !di.Attributes.HasFlag(FileAttributes.ReparsePoint)).Select(di => di.Name);
|
Path
|
using System.IO;
var filePath = @"C:\Dossier\fichier.txt"
Path.GetDirectoryName(filePath); // chemin dossier parent C:\Dossier
Path.GetFileName(Path.GetDirectoryName(filePath)); // nom du dossier parent Dossier
Path.GetExtension(filePath); // .txt
Path.GetFileName(filePath); // fichier.txt
Path.GetFileNameWithoutExtension(filePath); // fichier
Path.Combine(@"C:\AutreDossier", "fichier.odt"); // C:\AutreDossier\fichier.odt
// Concatène le chemin courant avec le chemin relatif
var cheminAbsolu = Path.GetFullPath(cheminRelatif)
|
Caractères interdits
|
var replacement = "";
var fileName = Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), replacement));
|
|
public static string GetRelativePath(string fromPath, string toPath)
{
int fromAttr = GetPathAttribute(fromPath);
int toAttr = GetPathAttribute(toPath);
StringBuilder path = new StringBuilder(260); // MAX_PATH
if(PathRelativePathTo(
path,
fromPath,
fromAttr,
toPath,
toAttr) == 0)
{
throw new ArgumentException("Paths must have a common prefix");
}
return path.ToString();
}
private static int GetPathAttribute(string path)
{
DirectoryInfo di = new DirectoryInfo(path);
if (di.Exists)
{
return FILE_ATTRIBUTE_DIRECTORY;
}
FileInfo fi = new FileInfo(path);
if(fi.Exists)
{
return FILE_ATTRIBUTE_NORMAL;
}
throw new FileNotFoundException();
}
private const int FILE_ATTRIBUTE_DIRECTORY = 0x10;
private const int FILE_ATTRIBUTE_NORMAL = 0x80;
[DllImport("shlwapi.dll", SetLastError = true)]
private static extern int PathRelativePathTo(StringBuilder pszPath,
string pszFrom, int dwAttrFrom, string pszTo, int dwAttrTo);
|
PathRelativePathTo function
- Les chemins avec dossiers + fichier sont d'une longueur maximale de 260
- Les chemins avec dossiers sans fichiers sont d'une longueur maximale de 248 (260-12)
Dossiers spéciaux de Windows
|
string path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
|
Énumération SpecialFolder
|
Chemin correspondant (7 64bits)
|
Windows
|
C:\Windows
|
System
|
C:\Windows\System32
|
SystemX86
|
C:\Windows\SysWOW64
|
UserProfile
|
C:\Users\<User Name>
|
MyDocuments
|
C:\Users\<User Name>\Documents
|
ApplicationData
|
C:\Users\<User Name>\AppData\Roaming
|
LocalApplicationData
|
C:\Users\<User Name>\AppData\Local
|
InternetCache
|
C:\Users\<User Name>\AppData\Local\Microsoft\Windows\Temporary Internet Files
|
ProgramFiles
|
C:\Program Files (x86)
|
WinForm
Ces propriétés ne sont disponible que pour les application WinForm.
|
// C:\Users\<User Name>\AppData\Roaming\<Company Name>\<Product Name>\<Product Version>
string path = Application.UserAppDataPath;
// C:\Users\<User Name>\AppData\Local\<Company Name>\<Product Name>\<Product Version>
string path = Application.LocalUserAppDataPath;
|
|
private static void DirectoryCopy(string sourcePath, string destinationPath, bool copySubDirectories)
{
var directory = new DirectoryInfo(sourcePath);
var directories = directory.GetDirectories();
if (!directory.Exists)
{
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + sourcePath);
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destinationPath))
{
Directory.CreateDirectory(destinationPath);
}
// Get the files in the directory and copy them to the new location.
var files = directory.GetFiles();
foreach (FileInfo file in files)
{
string destinationFilePath = Path.Combine(destinationPath, file.Name);
var destinationFile = new FileInfo(destinationFilePath);
if (destinationFile == null)
{
file.CopyTo(destinationFilePath, false);
}
else if (file.LastWriteTime > destinationFile.LastWriteTime)
{
file.CopyTo(destinationFilePath, true);
}
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirectories)
{
foreach (DirectoryInfo subDirectory in directories)
{
string destinationFolderPath = Path.Combine(destinationPath, subDirectory.Name);
DirectoryCopy(subDirectory.FullName, destinationFolderPath, copySubDirectories);
}
}
}
|
Uri et Webdav
|
string path = @"\\serveur@SSL\Webdav\Fichier.txt";
new Uri(path); // UriFormatException: + Invalid URI: The hostname could not be parsed.
// Exception dans les cas suivant
WebBrowser.Source = new Uri(path);
WebBrowser.NavigateToStream((new StreamReader(path)).BaseStream);
XDocument.Load(path);
XDocument.Load(new StreamReader(path));
var xd = new XmlDocument();
xd.Load(path);
xd.Load(new StreamReader(path));
|