IO etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
IO etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

2 Nisan 2018 Pazartesi

Directory Sınıfı

Giriş
Bu sınıf için şu satır dahil edilir.
using System.IO.Directory;
CreateDirectory metodu
Bu metod bir sürü exception fırlatabiliyor. Açıklaması şöyle.
  • IOException
    • The directory specified by path is a file.
    • The network name is not known.
  • UnauthorizedAccessException
    • The caller does not have the required permission.
  • ArgumentException
    • path is a zero-length string, contains only white space, or contains one or more invalid characters. You can query for invalid characters by using the GetInvalidPathChars method.
    • path is prefixed with, or contains, only a colon character (:).
  • ArgumentNullException
    • path is null.
  • PathTooLongException
    • The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters and file names must be less than 260 characters.
  • DirectoryNotFoundException
    • The specified path is invalid (for example, it is on an unmapped drive).
  • NotSupportedException
    • path contains a colon character (:) that is not part of a drive label ("C:\").
Alt dizinleriyle beraber tüm dizin yolunu yaratır.Şöyle yaparız.
string folderPath = @"...";
DirectoryInfo di = Directory.CreateDirectory(folderPath);
Eğer uzak bir makinede dizin yaratmak istersek şöyle yaparız
string path = @"\\16.166.187.121\c$\testingfolder\Features\Temp\";
DirectoryInfo di = Directory.CreateDirectory(path);
Şöyle bir hata alabiliriz.
Logon failure: unknown user name or bad password.
Delete metodu
Şöyle yaparız.
Directory.Delete("someFolder",true);
EnumerateFiles metodu - string
Linq kullanabilmemizi sağlar. Uzantısı belli dosyalar şöyle silinir.
var reg = new Regex(@"(\.jpg|\.jpeg|\.png|\.gif|\.bmp)$");

Directory.EnumerateFiles(@"C:\temp")
         .Where(file => reg.Match(file).Success).ToList()
         .ForEach(File.Delete)
EnumerateFiles metodu - string + string + SeachOption
Açıklaması şöyle.
Returns an enumerable collection of file names that match a search pattern in a specified path, and optionally searches subdirectories.
Şöyle yaparız.
if(Directory.EnumerateFiles(folder, "*.txt",SearchOption.TopDirectoryOnly).Any())
{...}
Exists metodu
Şöyle yaparız.
string voicelogPath = Application.StartupPath + "\\Voicelog\\";
if (!Directory.Exists(voicelogPath + folderName))
{
  Directory.CreateDirectory(voicelogPath + folderName);
}
GetAccesControl metodu
DirectorySecurity nesnesi döner. Şöyle yaparız.
DirectorySecurity secInfo = Directory.GetAccessControl(path);
GetDirectories metodu
Şöyle yaparız.
string[] directories = Directory.GetDirectories(@"d:\",
                                              "*",
                                              SearchOption.AllDirectories);
Eğer dizinlerden birisine erişim izni yoksa UnauthorizedAccessException alırız. Linq metodlarını da kullanabiliriz.
string dir = Directory.GetDirectories(@"D:\","App_data").FirstOrDefault();
GetDirectories düzenli ifadeyi desteklemez. Ancak basitçe şöyle yapabiliriz.
List<string> destDir1 = Directory.GetDirectories(folderPath, "*",
    SearchOption.AllDirectories)
        .Where(f => Regex.IsMatch(f, @"[\\/]\d+$")).ToList();
GetFiles metodu
GetFiles mutlak (absolute) veya göreceli (relative) yol ile çalışabilir. Bir string dizisi döner.
Şöyle yaparız. Alt dizinlere bakmaz.
string dirPath =...;
string[] files = Directory.GetFiles (dirPath);
Linq ile kullanmak için şöyle yaparız.
string[] files = Directory.GetFiles(@"...")
  .Select(x=> ...).ToArray();
GetFiles metodu - SearchPattern
Şöyle yaparız.
string[] files = Directory.GetFiles (dirPath, "*.txt");
GetFiles metodu - SearchPattern + SearchOptions
1. SearchOption.TopDirectoryOnly
Şöyle yaparız. Belirtilen dizinindeki png uzantılı dosyalar bulunur. Alt dizinlere bakmaz
string[] files = Directory.GetFiles("...","*.png",SearchOption.TopDirectoryOnly);
2. SearchOption.AllDirectories
Alt dizinlere filtre kullanarak bakmak için şöyle yaparız.
string[] files = Directory.GetFiles("...", "*.txt", SearchOption.AllDirectories);
Alt dizinlere filtre kullanarak erişip, linq ile kullanabilmek için şöyle yaparız.
DateTime endTime = DateTime.Now;
DateTime starttime = endTime.AddDays(-2);

var filesBetweenDates = Directory.GetFiles("...", "*.*",  SearchOption.AllDirectories)
  .Where(f => new FileInfo(f).CreationTime > starttime && 
         new FileInfo(f).CreationTime < endTime);
GetLogicalDrives metodu
Şöyle yaparız
string[] drives = Directory.GetLogicalDrives();
GetParent metodu
Şöyle yaparız.
System.IO.Directory.GetParent(@"D:/Sports/All/Indoor/TableTennis/Women/9.jpg").Name
SetAccessControl metodu
Şöyle yaparız.
string path = ...;
DirectorySecurity directorySecurity = ...;
Directory.SetAccessControl(path, directorySecurity);

25 Kasım 2016 Cuma

StreamWriter Sınıfı

Giriş
Şu satırı dahil ederiz. Bu sınıfın yazdığını okumak için StreamReader kullanılır.
using System.IO;
Stream sınıflarını using ile kapatmak gerekir. StreamWriter ve StreamReader sınıfları Stream'den kalıtırlar. Stream ise IDisposable arayüzünden kalıtır. Şöyle yaparız.
using (var sr = new StreamReader(...)) 
{
 ...
}
Constructor - String
Dosya mevcutsa sıfırlar. Şöyle yaparız.
using (StreamWriter sw = new StreamWriter("Logfile.txt")) {...}
Constructor - String + Append
Dosya varsa ekleme yapar. Şöyle yaparız. İkinci parametrenin anlamı şöyle
True: Append in file if exists
False: Overwrite file if exists

using (StreamWriter sw = new StreamWriter("Logfile.txt", true)) {...}
Constructor - String + Overwrite
Dosya mevcutsa sıfırlar. Şöyle yaparız. İkinci parametrenin anlamı şöyle
True: Append in file if exists
False: Overwrite file if exists
using (StreamWriter sw = new StreamWriter("Logfile.txt", false)) {...}
Constructor - Stream
Şöyle yaparız.
string file = "C:\\Temp\\registery.txt";
FileStream fOutStream = File.Open (file, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter (fOutStream);
AutoFlush Alanı
Şöyle yaparız.
sw.AutoFlush = true;
Close metodu
Açıklaması şöyle
This implementation of Close calls the Dispose method passing a true value.
Yani Close() çağırmak ile Dispose() çağırmak aynı kapıya çıkar.Şöyle yaparız.
sw.Close();
Flush metodu
Şöyle yaparız.
sw.Flush();
WriteLine metodu
Şöyle yaparız.
sw.WriteLine("...");