摘要:檔案處理
############################ 抓取目錄下檔案資訊 ###########################
private List<FileInfo> GetFiles()
{
List<FileInfo> lstFileInfo = new List<FileInfo>();
string dir = Server.MapPath("~/images");
FileInfo info;
string[] files;
files = Directory.GetFiles(dir);
foreach (string item in files)
{
info = new FileInfo(item);
lstFileInfo.Add(info);
}
return lstFileInfo;
}
########################### 建立目錄 #######################################
if (!Directory.Exists(Server.MapPath("~/abc/"))) //目錄中否存在
Directory.CreateDirectory(Server.MapPath("~/abc/")); //若不存在建立目錄
########################## txt 文字檔應用 ####################################
//-----------讀取文字-------------
方式一、
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
方式二、
using (StreamReader sr = File.OpenText(FILE_NAME))
{
String input;
while ((input=sr.ReadLine())!=null)
{
Console.WriteLine(input);
}
Console.WriteLine ("The end of the stream has been reached.");
sr.Close();
}
方式三、
string[] readText = File.ReadAllLines(path);
//寫入文字
File.AppendAllText(File.AppendAllText("檔案路徑", "要寫入的內容");
############################## 資料串流 ###############################
using System.IO;
############################## 將上傳檔案轉為二進位建立儲存 #################
ws_localhost.WebService ws = new ws_localhost.WebService();
if (ws.UploadFile(this.FileUpload1.FileBytes, this.FileUpload1.FileName))
Page.ClientScript.RegisterStartupScript(this.GetType(), "jsMessage", "alert('檔案已上傳成功!');", true);
else Page.ClientScript.RegisterStartupScript(this.GetType(), "jsMessage", "alert('上傳檔案失敗!');", true);
public bool UploadFile(byte[] fs, string fileName)
{
try
{
MemoryStream memoryStream = new MemoryStream(fs);
FileStream fileStream = new FileStream(Server.MapPath(@"~/wsDownFile/" + fileName), FileMode.Create);
memoryStream.WriteTo(fileStream);
memoryStream.Close();
fileStream.Close();
fileStream = null;
memoryStream = null;
return true;
}
catch (Exception ex)
{
return false;
}
}
################################## 利用streamWrtite 將文字寫入/檔案 / streamReader 讀取檔案 ##############
using (StreamWriter sw = File.CreateText(FILE_NAME))
{
sw.WriteLine ("This is my file.");
sw.Close();
}
using (StreamReader r = File.OpenText("log.txt"))
{
while ((line=r.ReadLine())!=null)
Console.WriteLine(line);
}
################################## ###########################################
___________________________________________________________________________
資料來源:http://msdn.microsoft.com/zh-tw/library/k3352a4t(v=VS.80).aspx