如果文件不存在则创建文件

如果文件不存在,我需要读取我的代码。现在它正在读取是否存在创建和追加。密码如下:

if (File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{

我会这么做吗?

if (! File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{

编辑:

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();
}

}

268816 次浏览

Yes, you need to negate File.Exists(path) if you want to check if the file doesn't exist.

You don't even need to do the check manually, File.Open does it for you. Try:

using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append)))
{

Ref: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx

You can simply call

using (StreamWriter w = File.AppendText("log.txt"))

It will create the file if it doesn't exist and open the file for appending.

Edit:

This is sufficient:

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);
}
}

But if you insist on checking first, you can do something like this, but I don't see the point.

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);
}
}

Also, one thing to point out with your code is that you're doing a lot of unnecessary unboxing. If you have to use a plain (non-generic) collection like ArrayList, then unbox the object once and use the reference.

However, I perfer to use List<> for my collections:

public class EmployeeList : List<Employee>

or:

using FileStream fileStream = File.Open(path, FileMode.Append);
using StreamWriter file = new StreamWriter(fileStream);
// ...

For Example

    string rootPath = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));
rootPath += "MTN";
if (!(File.Exists(rootPath)))
{
File.CreateText(rootPath);
}
private List<Url> AddURLToFile(Urls urls, Url url)
{
string filePath = @"D:\test\file.json";
urls.UrlList.Add(url);


//if (!System.IO.File.Exists(filePath))
//    using (System.IO.File.Delete(filePath));


System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(urls.UrlList));


//using (StreamWriter sw = (System.IO.File.Exists(filePath)) ? System.IO.File.AppendText(filePath) : System.IO.File.CreateText(filePath))
//{
//    sw.WriteLine(JsonConvert.SerializeObject(urls.UrlList));
//}
return urls.UrlList;
}


private List<Url> ReadURLToFile()
{
//  string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"App_Data\file.json");
string filePath = @"D:\test\file.json";


List<Url> result = new List<Url>(); ;
if (!System.IO.File.Exists(filePath))
using (System.IO.File.CreateText(filePath)) ;






using (StreamReader file = new StreamReader(filePath))
{
result = JsonConvert.DeserializeObject<List<Url>>(file.ReadToEnd());
file.Close();
}
if (result == null)
result = new List<Url>();


return result;


}

This works as well for me

string path = TextFile + ".txt";


if (!File.Exists(HttpContext.Current.Server.MapPath(path)))
{
File.Create(HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine("{0}", "Hello World");
w.Flush();
w.Close();
}

This will enable appending to file using StreamWriter

 using (StreamWriter stream = new StreamWriter("YourFilePath", true)) {...}

This is default mode, not append to file and create a new file.

using (StreamWriter stream = new StreamWriter("YourFilePath", false)){...}
or
using (StreamWriter stream = new StreamWriter("YourFilePath")){...}

Anyhow if you want to check if the file exists and then do other things,you can use

using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
{...}

2021

Just use File.AppendAllText, which creates the file if it does not exist:

File.AppendAllText("myFile.txt", "some text");