IO 常用

1. read file from folder 

DirectoryInfo folder = new DirectoryInfo(@"C:\Users\keatkeat\Desktop\Kids cartoon");
FileInfo[] Files = folder.GetFiles();       
foreach (FileInfo file in Files)
{
                              

}

 

2. read file from folder and all nested subfolder  

var path = HostingEnvironment.WebRootPath + @"\new-sounds";
var allfiles = Directory.GetFiles("path/to/dir", "*.*", SearchOption.AllDirectories);
foreach (var file in allfiles)
{
    var info = new FileInfo(file);
}

 

 

3. create text file

if (!Directory.Exists(Path.GetDirectoryName(fullPath)))
{
    Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
}
if (!File.Exists(fullPath))
{
    File.Create(fullPath).Dispose();
}
using (TextWriter tw = new StreamWriter(fullPath))
{
    tw.WriteLine(content);
}

 

4. 打开 file 时设置读写锁

 using (var fs = File.Open(path, FileMode.Open, FileAccess.Write, FileShare.Read)) // e.g. 我写的时候人家不可以写,但是可以读.
{
}

 

posted @ 2016-07-16 17:30  兴杰  阅读(238)  评论(0编辑  收藏  举报