Вопрос

I am using Visual Studio 2013 and C#

I currently have a form which, among other items, has a textbox for the user to enter an id number. I want to be able to 'take' this number and create a text file with the ID number as a file name.

I have been able to write to a file using the OpenFileDialog and Streamwriter, but this requires the user to click the "Save Location" button and browse to a file location, then enter the text for the file they want created.

I would rather have the program create the .txt file based on the id number so that they can just enter their ID and then press enter to start the program.

Is this possible?

Это было полезно?

Решение

Yes it's possible and it's trivial to do. If you want to use your StreamWriter just replace my File.WriteAllText with your StreamWriter code.

button_click_handler(fake args)
{
     string fileName = MyTextBox.Text;
     File.WriteAllText(basePath + fileName, "file contents");
}

Другие советы

Of course it is possible. The only point not clear in your question is where you want to create this text file and what you want to store inside it.

 string fileName = txtForFileName.Text;
 // create a path to the MyDocuments folder
 string docPath = Environment.GetFolderPath(Environment.SpecialFolders.MyDocuments);
 // Combine the file name with the path
 string fullPath = Path.Combine(docPath, fileName);

 // Note that if the file exists it is overwritten
 // If you want to APPEND then use: new StreamWriter(fullPath, true)
 using(StreamWriter sw = new StreamWriter(fullPath))
 {
    sw.WriteLine("Hello world");
 }

I think that you could find very useful looking at this MSDN page about Common I/O Tasks

There's a lot of ways to do that.

 string thepath = String.Format("{0}{1}{2}","C:\\PutDestinationHere\\",idTextBox.text,".txt");

 using(StreamWriter writer = new StreamWriter(thepath))
  {
     writer.WriteLine();
  }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top