0

I want to create a text file using the content of a TextBox as input.
When I run my app, I get this error when trying to execute this task on button click:

System.IO.IOException: 'The filename, directory name, or volume label syntax is incorrect: 'C:\Users\Jason\source\repos\App1\App1\bin\Debug\netcoreapp3.1@C:\Users\Jason\Desktoppptest.txt''

Here's my code:

private void button1_Click(object sender, EventArgs e)
{
    string filename = ("@C:\\Users\\Jason\\Desktop\app") + (textBox2.Text) + (".txt");
    File.Create(filename);
}
Jimi
  • 29,621
  • 8
  • 43
  • 61
  • 1
    What is the content of your TextBox? Why are you using all those parentheses? Have you tried to use `Path.Combine()`? The path mentioned in the exception seems to include the app path. – Jimi Jul 28 '21 at 11:18
  • I'm not sure why I added all of those, I was seeing if it would make any difference. The textbox will hold what the new text file will be called and, on button press, the app will create it. I haven't looked into `Path.Combine()` as I've never heard of it. –  Jul 28 '21 at 11:21
  • Putting [`@`](https://stackoverflow.com/q/556133/1997232) inside a string is a typo. – Sinatr Jul 28 '21 at 11:26
  • Where do you want to create this file? In the application path (`Application.StartupPath`) or in a folder of the current User's desktop? Both? -- The verbatim is inside the string, it should be *outside* . The path to the User's Desktop is a *Special Folder* ([Enviromnment.SpecialFolder.Desktop](https://learn.microsoft.com/en-us/dotnet/api/system.environment.specialfolder)) – Jimi Jul 28 '21 at 11:26

4 Answers4

0

Put the @ sign before quotation mark. The path must not contain the @ sign.

Also, see https://learn.microsoft.com/en-us/dotnet/api/system.io.path?view=net-5.0. This is handful when dealing with directories.

The second problem is that you're trying to concatenate two separate directories. Generate only one in order to create a file correctly. It should look this way.

C:\Users\Jason\source\repos\App1\App1\bin\Debug\netcoreapp3.1\test.txt'.

0

I don't know why you use a () to concatenate those string. And add another \ if that app in your filename is a folder. This should work:

private void button1_Click(object sender, EventArgs e)
{
    string filename = @"C:\Users\Jason\Desktop\app\" + textBox2.Text + ".txt";
    File.Create(filename);
}
Andrei Solero
  • 802
  • 1
  • 4
  • 12
0

set the file name as below. There should be a app folder on desktop.

string filename = @"C:\Users\Jason\Desktop\app" + textBox2.Text + ".txt";

Manoj
  • 81
  • 7
0

Quick way to test situations like this is to write them in something like LinqPad (or an online compiler) and outputing the string with WriteLine - this is the quickest way to validate if the string is what you want

In your situation you would see something like this:

LINQPAD example

string filename = "C:\\Users\\Jason\\Desktop\\app\\" + textBox2.Text + ".txt";

PawZaw
  • 1,033
  • 7
  • 15