C# 创建文件时,文件夹不存在,如何自动创建文件夹
生活随笔
收集整理的這篇文章主要介紹了
C# 创建文件时,文件夹不存在,如何自动创建文件夹
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
c# 創建文件時怎么創建文件夾?
strhtml=......
StreamWriter sw=new StreamWriter("D:/test/1.aspx",false);
sw.Write(strhtml);
如上代碼,如果test文件夾不存在就會報錯,需要先創建test文件夾才會正常產生1.aspx文件,問題:如何動態的自動創建文件夾呢?就是說一個路徑,如果有文件夾不存在,就自動創建該文件夾,該如何做?
------解決方案--------------------
Directory.CreateDirectory(filename);
------解決方案--------------------
先分離出文件夾路徑,Directory.CreateDirectory創建
------解決方案--------------------
C# code
FileInfo fi = new FileInfo("D:/test/1.aspx");
var di = fi.Directory;
if (!di.Exists)
di.Create();
------解決方案--------------------
public static void Write(string txt,string path,string filename)
{
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
StreamWriter sw = new StreamWriter(path, false);
sw.Write(txt);
}
------解決方案--------------------
/// <summary>
/// 創建文件夾
/// </summary>
/// <param name="FileUrl">路徑</param>
public static void CreateFile(string FileUrl)
{
Directory.CreateDirectory(FileUrl);
}
/// <summary>
/// 創建子文件
/// </summary>
/// <param name="FileUrl">路徑</param>
/// <param name="matter">內容</param>
public static void CreateTxt(string FileUrl, string matter)
{
//if (!File.Exists(url)) { }
FileStream fs = new FileStream(FileUrl, FileMode.Create, FileAccess.Write);//創建寫入文件
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(matter);//開始寫入值
sw.Close();
fs.Close();
}
------解決方案--------------------
C# code
string directoryPath = @"D: est";//定義一個路徑變量
string filePath = "1.txt";//定義一個文件路徑變量
if (!Directory.Exists(directoryPath))//如果路徑不存在
{
Directory.CreateDirectory(directoryPath);//創建一個路徑的文件夾
}
StreamWriter sw = new StreamWriter(Path.Combine(directoryPath, filePath));
sw.Write("test");
sw.Flush();
sw.Close();
------解決方案--------------------
C# code
//以下代碼實現了創建文件夾
if (!Directory.Exists(sPath))
{
Directory.CreateDirectory(sPath);
}
------解決方案--------------------
這個上面都回答了
------解決方案--------------------
上面都答完了,反正創建文件時,先用代碼判斷文件夾存不存在,不存在就先建文件夾,再建文件。
------解決方案--------------------
string directoryPath = @"D: est";//定義一個路徑變量
string filePath = "1.txt";//定義一個文件路徑變量
if (!Directory.Exists(directoryPath))//如果路徑不存在
{
Directory.CreateDirectory(directoryPath);//創建一個路徑的文件夾
}
StreamWriter sw = new StreamWriter(Path.Combine(directoryPath, filePath));
sw.Write("test");
sw.Flush();
sw.Close();
------解決方案--------------------
string path = Server.MapPath("~/UpLoadFiles/MyFile/");
if (!Directory.Exists(path))
{
//創建文件夾
Directory.CreateDirectory(path);
}
------解決方案--------------------
我跟上面的想法是差不多的
------解決方案--------------------
string directoryPath = @"D: est";//定義一個路徑變量
string filePath = "1.txt";//定義一個文件路徑變量
if (!Directory.Exists(directoryPath))//如果路徑不存在
{
Directory.CreateDirectory(directoryPath);//創建一個路徑的文件夾
}
StreamWriter sw = new StreamWriter(Path.Combine(directoryPath, filePath));
sw.Write("test");
sw.Flush();
sw.Close();
總結
以上是生活随笔為你收集整理的C# 创建文件时,文件夹不存在,如何自动创建文件夹的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ATPG原理及实现——11.Diagno
- 下一篇: HTML表格与表单