C# 產生Folder and 文字檔

  • 561
  • 0

1.在C槽的Folder:DemoCreateTXTFile底下產生一個系統日期資料夾,如果不存在就自動產生

2.紀錄類別Path提供的功能

1.在C槽的Folder:DemoCreateTXTFile底下產生一個系統日期資料夾,如果不存在就自動產生

//在C槽的Folder:DemoCreateTXTFile底下產生一個系統日期資料夾,如果不存在就自動產生
String FilePath = "C:" + Path.DirectorySeparatorChar.ToString() + "DemoCreateTXTFile" + Path.DirectorySeparatorChar
	+ DateTime.Now.ToString("yyyyMMdd") + Path.DirectorySeparatorChar.ToString();

//如果Folder不存在,自動產生這個Folder
if (!Directory.Exists(FilePath))
{
	Directory.CreateDirectory(FilePath);
}

String LogFile = FilePath + Path.DirectorySeparatorChar.ToString() + DateTime.Now.ToString("yyyyMMdd") + ".txt";

StreamWriter sw = new StreamWriter(LogFile, true);
try
{
	sw.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " -- 測試寫入文字檔");
}
catch (Exception ex)
{
}
finally
{
	//記得要close,或是使用下面的using寫法
	sw.Close();
}

//using (StreamWriter sw = new StreamWriter(LogFile, true))
//{
//    sw.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + " -- 測試寫入文字檔");
//}

2.紀錄類別Path提供的功能

//指定路徑底下的檔案存在
if (File.Exists(FilePath))
{
	String FullPath = "取得完整路徑:" + Path.GetFullPath(FilePath);
	String PathRoot = "取得根目錄" + Path.GetPathRoot(FilePath);
	String DirectoryName = "取得目錄名" + Path.GetDirectoryName(FilePath);

	String FileName = "取得完整檔名:" + Path.GetFileName(FilePath);
	String FileNameWithoutExtension = "取得檔名:" + Path.GetFileNameWithoutExtension(FilePath);
	String FileExtension = "取得副檔名:" + Path.GetExtension(FilePath);

	//變更副檔名 
	//Path.ChangeExtension(FilePath, ".cs");

	String CombinePathName = "結合路徑:" + Path.Combine(FilePath + Path.DirectorySeparatorChar.ToString() + "Path_1" + Path.DirectorySeparatorChar.ToString());

	char a = Path.DirectorySeparatorChar; //目錄分隔字元: "\"
	char b = Path.VolumeSeparatorChar; //磁碟分隔字元: ":"
	char c = Path.PathSeparator; //路徑分隔字元: ";"

	String _DirectorySeparatorChar = "目錄分隔字元:" + Path.DirectorySeparatorChar.ToString();
	String _VolumeSeparatorChar = "磁碟分隔字元:" + Path.VolumeSeparatorChar.ToString();
	String _PathSeparator = "路徑分隔字元:" + Path.PathSeparator.ToString();

	using (StreamWriter sw = new StreamWriter(FilePath, true))
	{
		sw.WriteLine(FullPath);
		sw.WriteLine(PathRoot);
		sw.WriteLine(DirectoryName);

		sw.WriteLine(FileName);
		sw.WriteLine(FileNameWithoutExtension);
		sw.WriteLine(FileExtension);

		sw.WriteLine(CombinePathName);

		sw.WriteLine(_DirectorySeparatorChar);
		sw.WriteLine(_VolumeSeparatorChar);
		sw.WriteLine(_PathSeparator);
	}
}

執行結果如下: