[英]StreamWriter and FileStream errors on file create
我的 Controller 中有一個 Save ActionResult,它設置為使用 StreamWriter。 該代碼完美地工作,用於保存到存在的文件。
保存操作
[HttpPost]
[ValidateInput(false)]
public ActionResult Save(string fileName, string startTemplateUrl, string html)
{
string directoryname = Path.GetDirectoryName(fileName);
string filename = Path.GetFileName(fileName);
var lines = html;
var helper = (Server.MapPath(directoryname));
using (StreamWriter outputFile = new StreamWriter(Path.Combine(helper, filename)))
{
outputFile.WriteLine(lines);
return View();
}
}
我現在正在創建文件,從我所讀到的內容中,您可以使用 StreamWriter 執行此操作,盡管當我嘗試實現它時,它說找不到它。 這告訴我它正在尋找一個文件而不是創建它。
所以我嘗試使用 FileInfo 來實現它。 它似乎擁有它需要的一切,但只是不保存它。 下面是我最新的代碼。 它不喜歡
fs.Write(lines);
我有一個 try catch 塊。 在這一點上,它有相同的結果。 它找不到它。
[HttpPost]
[ValidateInput(false)]
public ActionResult Create (string fileName, string startTemplateUrl, string html)
{
string directoryname = Path.GetDirectoryName(fileName);
string filename = Path.GetFileName(fileName);
var lines = html;
var helper = (Server.MapPath(directoryname));
var file = "Test\\" + filename;
var pathString = System.IO.Path.Combine(helper, "Test\\", filename);
FileInfo fi = new FileInfo(pathString);
if (fi.Exists)
{
fi.Delete();
}
using (FileStream fs = fi.Create())
{
fs.Write(lines);
return View();
}
}
謝謝你的幫助!
更新:
這是我得到的信息。 在消息下方,我有從文件夾資源管理器復制的目錄的實際字符串..
Exception thrown: 'System.IO.DirectoryNotFoundException' in mscorlib.dll
An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code
Could not find a part of the path 'C:\Users\Scott\source\repos\HMIBuilder\HMIBuilder\Files\HMIBuider\Test\Test2.html'.
C:\Users\Scott\source\repos\HMIBuilder\HMIBuilder\Files\HMIBuilder\Test
更新:
我需要更好地查看我的代碼。 這是固定的。最頂部的代碼非常適合保存和創建。 問題出在我提供給它的 javascript 代碼變量中。 一個錯字..,如果你看上面的比較,我沒有發現自己,我想有太多漫長的夜晚了。 HMIBuilder 在錯誤中拼寫為 HMIBuider...。
using (StreamWriter outputFile = new StreamWriter(Path.Combine(path, "filename.txt")))
如果需要,將創建一個新文件。
您的問題可能出在Test
目錄上,而CreateDirectory
可以為您提供幫助。
DirectoryInfo di = Directory.CreateDirectory(path);
如果我們將寫入文件和創建目錄放在一起,它可能看起來像下面的代碼片段。
var path = "./MyFiles/SpecialFiles";
var filename = "thisIsAVerySpecialFile.txt";
Directory.CreateDirectory(path);
//Create a new file or overwrite existing (i.e. *not* append)
using (var f = new StreamWriter(Path.Combine(path, filename)))
{
f.WriteLine("Hello world!");
}
如果沒有Directory.CreateDirectory
,代碼會導致System.IO.DirectoryNotFoundException
出現'Could not find a part of the path '(...)'.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.