I wonder if there is any way to make the file saved with a variable as its name. Any ideas? Please help! :)
Printable View
I wonder if there is any way to make the file saved with a variable as its name. Any ideas? Please help! :)
The name of a file is just a string. If you variable contains a string then its as good a choice as any other string. There's no functional difference between this:and this:vb.net Code:
IO.File.WriteAllText("MyFile.txt", "Hello World")vb.net Code:
Dim fileName As String = "MyFile.txt" IO.File.WriteAllText(fileName, "Hello World")
There is definitely a way - simply replace the text of the file name with your variable name by using the & operator to combine the strings together (as I assume you already have the directory path where this would be saved in another string).
If I have a RichTextBox1, and I want to save the text inside into txt file with a variable file name. How to do it? I mean how to assign the rtbox1 for it to save? Thanks!
Thats completely different to the original question but its the same kind of answer. Assign the text to a variable and then use the variable where you would have to otherwise type a literal string.Quote:
I mean how to assign the rtbox1 for it to save?
Having said that, the RTB control has a SaveFile method which you can use in this specific case. Example:
So if you wanted to use a variable as the file name, you could do this (obviously this example just saves it in the root of the C drive but you get the idea) :vb Code:
RichTextBox1.SaveFile("C:\example.txt")
Where obviously MyVariable is your variable that contains the file name.vb Code:
RichTextBox1.SaveFile("C:\" & MyVariable)
To do it more 'properly' you can use IO.Path.Combine as well, like so:
vb Code:
RichTextBox1.SaveFile(IO.Path.Combine("C:\", MyVariable))