我正在嘗試將 List 的所有內容保存到文本檔案中,但我無法做到。以下是我嘗試過的代碼
// here is my list type
List<string> list2 = new List<string>();
//code below for saving the contents of the list into text file
string file = @"C:\Users\textWriter.txt";
// check if the file exists
try
{
if (File.Exists(file))
{
File.Delete(file);
}
else
{
using (TextWriter tw = File.CreateText(@"SavedList.txt"))
{
foreach (String s in list2)
tw.WriteLine(s);
}
}
}
catch (Exception Op)
{
MessageBox.Show(Op.Message);
}
uj5u.com熱心網友回復:
不確定是什么例外,但我強烈建議改用它:
File.WriteAllLines(file, list2);
如果目標檔案已存在,則將其覆寫。
檔案:File.WriteAllLines
在您的代碼中,您使用不同的路徑,也許這就是原因
uj5u.com熱心網友回復:
您在 (File.Exists(file) 和 File.CreateText(@"SavedList.txt") 中有不同的路徑。接下來,您是否在 List 中添加了元素?
uj5u.com熱心網友回復:
問題已經解決了。使用@Tim Schmelter 建議的更新代碼以及此鏈接的幫助C# access to the path is denied...(System.UnauthorizedAccessException: Access to the path 'C:\' is denied.),我現在可以看到寫入所有內容的檔案。
string file = @"D:\textWriter.txt";
// check if the file exists
try
{
if (File.Exists(file))
{
File.Delete(file);
}
else
{
File.WriteAllLines(file, list2);
}
}
catch (Exception Op)
{
MessageBox.Show(Op.Message);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/460961.html
標籤:C# 仿制药 文件-io streamwriter.write
下一篇:如何使用硒單擊按鈕
