我需要让我的代码读取文件是否存在创建else附加.现在它正在读取它是否确实存在创建和追加.这是代码:
if (File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
Run Code Online (Sandbox Code Playgroud)
我会这样做吗?
if (! File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
Run Code Online (Sandbox Code Playgroud)
编辑:
string path = txtFilePath.Text;
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
}
}
else
{
StreamWriter sw = File.AppendText(path);
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
sw.Close();
}
Run Code Online (Sandbox Code Playgroud)
}
Chr*_*ler 99
你可以简单地打电话
using (StreamWriter w = File.AppendText("log.txt"))
Run Code Online (Sandbox Code Playgroud)
如果文件不存在,它将创建该文件并打开文件以进行追加.
编辑:
这就足够了:
string path = txtFilePath.Text;
using(StreamWriter sw = File.AppendText(path))
{
foreach (var line in employeeList.Items)
{
Employee e = (Employee)line; // unbox once
sw.WriteLine(e.FirstName);
sw.WriteLine(e.LastName);
sw.WriteLine(e.JobTitle);
}
}
Run Code Online (Sandbox Code Playgroud)
但如果你坚持先检查,你可以做这样的事情,但我不明白这一点.
string path = txtFilePath.Text;
using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
{
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
}
Run Code Online (Sandbox Code Playgroud)
此外,有一点要指出的是你的代码是你做了很多不必要的拆箱.如果必须使用普通(非泛型)集合ArrayList,则将对象取消装箱一次并使用引用.
但是,我更喜欢List<>用于我的收藏:
public class EmployeeList : List<Employee>
Run Code Online (Sandbox Code Playgroud)
Mit*_*nca 17
要么:
using(var fileStream = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(path, true))
{
//...
}
}
Run Code Online (Sandbox Code Playgroud)
And*_*dee 13
你甚至不需要手动进行检查,File.Open会为你做.尝试:
using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append)))
{
Run Code Online (Sandbox Code Playgroud)
参考:http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx
2021年
只需使用File.AppendAllText,如果文件不存在,它会创建该文件:
File.AppendAllText("myFile.txt", "some text");
Run Code Online (Sandbox Code Playgroud)
是的,File.Exists(path)如果要检查文件是否不存在,则需要否定.
| 归档时间: |
|
| 查看次数: |
181035 次 |
| 最近记录: |