C Sharp File

From Leo's Notes
Last edited on 5 April 2015, at 23:01.

Here are some common file operations you can do in C#.

System.IO.File

Exists()

Checks whether a file exists.

if (File.Exists(@"C:\test.txt")) 

System.IO.Path

DirectorySeparatorChar

Returns the directory separator character depending on the platform.

Windows: \
Unix: /

GetFullPath()

Converts a relative path to a full path.

Path.GetFileNameWithoutExtension(@"test.txt")
-> returns "C:\test.txt", depending on your current working directory

GetDirectoryName()

Returns the directory path to the given file.

Path.GetDirectoryName(@"C:\dir\test\test.txt")
-> returns "C:\dir\test"

GetFileNameWithoutExtension()

Returns only the file name without extension

Path.GetFileNameWithoutExtension(@"C:\test.txt")
-> returns "test"

GetExtension()

Returns the '.ext' file extension.

Path.GetExtension(@"C:\test.txt")
-> returns ".txt"