Files
File exists
using System.IO;
bool exists = File.Exists("myfile.txt"); |
using System.IO;
bool exists = File.Exists("myfile.txt");
Get all file content in a String
using System.IO;
String contents = File.ReadAllText("myfile.txt"); |
using System.IO;
String contents = File.ReadAllText("myfile.txt");
Write all content string to a File
using System.IO;
File.WriteAllText("myfile.txt", "hello world !!", Encoding.UTF8); |
using System.IO;
File.WriteAllText("myfile.txt", "hello world !!", Encoding.UTF8);
Directories
Directory exists
using System.IO;
bool exists = Directory.Exists("my/dir"); |
using System.IO;
bool exists = Directory.Exists("my/dir");
Create Directory
using System.IO;
DirectoryInfo dirInfo = Directory.CreateDirectory("my/dir");
bool exists = dirInfo.Exists; |
using System.IO;
DirectoryInfo dirInfo = Directory.CreateDirectory("my/dir");
bool exists = dirInfo.Exists;
Test if directory is readonly
using System.IO;
DirectoryInfo dirInfo = new DirectoryInfo("my/dir");
bool isReadOnly = (dirInfo.Attributes & FileAttributes.ReadOnly) > 0;
// Note, if you want to remove ReadOnly attributes:
// dirInfo.Attributes = dirInfo .Attributes & ~FileAttributes.ReadOnly; |
using System.IO;
DirectoryInfo dirInfo = new DirectoryInfo("my/dir");
bool isReadOnly = (dirInfo.Attributes & FileAttributes.ReadOnly) > 0;
// Note, if you want to remove ReadOnly attributes:
// dirInfo.Attributes = dirInfo .Attributes & ~FileAttributes.ReadOnly;
Get directory name
using System.IO;
String dirname = Path.GetDirectoryName("my/dir"); |
using System.IO;
String dirname = Path.GetDirectoryName("my/dir");
IDisposable implementation, how to use “using” instruction ?
Instead of writing something like this :
StreamReader reader = new StreamReader(myfile.txt");
try
{
s = reader.ReadLine();
}
finally
{
reader.Close();
} |
StreamReader reader = new StreamReader(myfile.txt");
try
{
s = reader.ReadLine();
}
finally
{
reader.Close();
}
you can write this :
using (StreamReader reader = new StreamReader("myfile.txt"))
{
s = reader.ReadLine();
}
// here is called "reader.Dispose()". |
using (StreamReader reader = new StreamReader("myfile.txt"))
{
s = reader.ReadLine();
}
// here is called "reader.Dispose()".