#region 檔案讀取與儲存
/// <summary>
/// 擷取檔案中的資料串
/// </summary>
public static string fileToString(String filePath)
{
string str = "";
//擷取檔案内容
if (System.IO.File.Exists(filePath))
{
System.IO.StreamReader file1 = new System.IO.StreamReader(filePath);//讀取檔案中的資料
str = file1.ReadToEnd(); //讀取檔案中的全部資料
file1.Close();
file1.Dispose();
}
return str;
}
/// <summary>
/// 儲存資料data到檔案處理過程,傳回值為儲存的檔案名
/// </summary>
public static String SaveProcess(String data, String name)
{
string CurDir = System.AppDomain.CurrentDomain.BaseDirectory + @"SaveDir\"; //設定目前目錄
if (!System.IO.Directory.Exists(CurDir)) System.IO.Directory.CreateDirectory(CurDir); //該路徑不存在時,在目前檔案目錄下建立檔案夾"導出.."
//不存在該檔案時先建立
String filePath = CurDir + name + ".txt";
System.IO.StreamWriter file1 = new System.IO.StreamWriter(filePath, false); //檔案已覆寫方式添加内容
file1.Write(data); //儲存資料到檔案
file1.Close(); //關閉檔案
file1.Dispose(); //釋放對象
return filePath;
}
#endregion
儲存資料到檔案:
/// <summary>
/// 儲存資料data到檔案,傳回值為儲存的檔案名
/// </summary>
public string SaveToFile(String data, String name, bool mute)
{
String filePath = "";
//若未命名,則使用系統時間自動命名
if (name == null || name.Trim().Equals("(重命名)") || name.Trim().Equals(""))
{
name = DateTime.Now.ToLongTimeString().Replace(":", "."); //使用系統時間自動為檔案命名
filePath = SaveToFile(data, name, false); //儲存資料到檔案
return filePath; //傳回儲存的檔案名
}
try
{
filePath = SaveProcess(data, name); //儲存資料并記錄檔案完整路徑
if (!mute) MessageBox.Show("成功導出資料到:“" + filePath + "”!");
return filePath;
}
catch (Exception)
{
MessageBox.Show("儲存資料失敗");
return "";
}
}
/// <summary>
/// 儲存資料data到原檔案filePathName中
/// </summary>
public String SaveToNativeFile(String data, String filePathName, bool mute)
{
try
{
System.IO.StreamWriter file1 = new System.IO.StreamWriter(filePathName, false); //檔案已覆寫方式添加内容
file1.Write(data); //儲存資料到檔案
file1.Close(); //關閉檔案
file1.Dispose(); //釋放對象
if (!mute) MessageBox.Show("成功導出資料到:“" + filePathName + "”!");
return filePathName;
}
catch (Exception)
{
return SaveToFile(data, "", mute); //若儲存到原檔案失敗,則建立新檔案進行儲存
}
}