0

I'm still a newbie for C#. I just want to know if it's possible that an input from textbox will be the name of your textfile?

Example: I input test in textbox, then the the name of my textfile or my textfile would be test.txt

I tried this, but it doesn't work:

string filename = textBox1.Text;

            string path = Path.Combine(@"E:\Majel\Tic Tac Toe\TextFiles", filename+".txt");

I really need your help. How to this? Thank you

4 Answers4

1

You only generated the file path with your code, but did not create any file. Try this:

string mypath = Path.Combine(@"E:\Majel\Tic Tac Toe\TextFiles\", filename+".txt");
System.IO.FileInfo f = new System.IO.FileInfo(mypath);
// make sure your folder path is valid
elimad
  • 1,132
  • 1
  • 15
  • 27
  • Sir,can you provide the whole code on how to do that? I tried this **string filename = textBox1.Text + ".txt"; string path = System.IO.Path.Combine(@"E:\Majel\Tic Tac Toe\TextFiles\", filename); System.IO.FileInfo f = new System.IO.FileInfo(path);** but still it doesn't work. – user3349418 Sep 27 '14 at 06:33
  • Check this. http://stackoverflow.com/questions/7569904/easiest-way-to-read-from-and-write-to-files – elimad Sep 27 '14 at 06:41
0

I you want litle change

string filename=txtfilename.text;
string path = System.IO.Path.Combine(@"E:\Majel\Tic Tac Toe\TextFiles\", filename + ".txt");
File.Create(path);

you try also

     string filename = textBox1.text;
     string path = System.IO.Path.Combine(@"E:\", filename + ".txt");
     System.IO.FileInfo file = new System.IO.FileInfo(path);
     file.Create();
      if (File.Exists(path))
          {
           TextWriter tw = new StreamWriter(path, true);
           tw.WriteLine("The next line!");
           tw.Close(); 
         }
     filename =string.Empty;
     textBox1.text=string.Empty;

try this

        string filename = txtfilename.text;
        string path = System.IO.Path.Combine(@"D:\", filename + ".txt");
        FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
        StreamWriter str = new StreamWriter(fs);
        str.BaseStream.Seek(0, SeekOrigin.End);
        str.Write("mytext.txt.........................");
        str.WriteLine(DateTime.Now.ToLongTimeString() + " " +
                      DateTime.Now.ToLongDateString());
        string addtext = "this line is added" + Environment.NewLine;
        str.Flush();
        str.Close();
        fs.Close();
Kishan
  • 1,182
  • 12
  • 26
0

Try this...

string filename = textBox1.Text.Trim() + ".txt";
string path = Path.Combine(@"E:\Majel\Tic Tac Toe\TextFiles\", filename);
Amit Philips
  • 387
  • 6
  • 17
0

Below code is on how you create text file using FileInfo

string filename = textBox1.Text;
string path = System.IO.Path.Combine(@"E:\Majel\Tic Tac Toe\TextFiles\", filename + ".txt");
System.IO.FileInfo file = new System.IO.FileInfo(path);
file.Create();
Kishan
  • 1,182
  • 12
  • 26
jayvee
  • 160
  • 2
  • 17