Jane
Jane

Reputation: 11

creating a textfile and cannot identify the location the created file goes

What is wrong with this code? The text file is not created in the bin\Debug directory!

string path = Environment.CurrentDirectory + "/" + "Contacts.txt";

if (!File.Exists(path))
{
    File.CreateText(path);
    MessageBox.Show("file created successfully");
}

using (StreamWriter sw = new StreamWriter("path", true))
{
    sw.WriteLine(txtCntname1.Text + "," + txtCntnum1.Text + "," + txtCntnum2.Text + "," + txtCntnum3.Text + ",");
    sw.Close();
}

Upvotes: 1

Views: 78

Answers (2)

Tobias Tengler
Tobias Tengler

Reputation: 7454

Aside from that path should probably not be in quotes here:

using (StreamWriter sw = new StreamWriter("path", true))

Do not use Environment.CurrentDirectory! It does not always represent the directory you started your executable from, since it only represents your working directory.

Please use Assembly.GetExecutingAssembly().Location to get the full path of the executing assembly and then extract only the directory from it, using:

Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)

Alternatively you could also use AppDomain.CurrentDomain.BaseDirectory for identifying the directory your application is residing in.

Of course not using an absolute path is a possibility as well, you can create your file using a relative path, by not specifying any directory:

File.CreateText("Contacts.txt")

EDIT:

Seeing how you formed your path, please also use Path.Combine to build your paths:

var appBaseDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var contactsFilePath = Path.Combine(appBaseDir, "Contacts.txt");

Upvotes: 1

JohnyL
JohnyL

Reputation: 7142

You have two ways of calculating EXE's directory:

1) Implicit

You can use only the file name. In this case, the file will be created in the same folder with EXE file:

File.CreateText("Contacts.txt")

2) Explicit

If you need reliable way to get the EXE's directory, then you need to use AppDomain:

string exe_dir = AppDomain.CurrentDomain.BaseDirectory;

Then, instead of manually concatenating strings to form a path, use Path.Combine method:

string file_path = Path.Combine(exe_dir, "Contact.txt");

The code (Assembly.GetExecutingAssembly().Location), offered by @TobiasTengler, won't work, for instance, for Excel/Word add-in.

Upvotes: 1

Related Questions