-1

In VB, I want to dynamically create a new text file in a hard-coded file share, based on the current user logged in.

I have tested the below code, which does indeed create the test file in the specified path, but i want the test.txt file name to be dynamic, im thinking based on the environment.username class?

Dim objwriter As New System.IO.StreamWriter("\\server\path\test.txt")
objwriter.WriteLine("first line")
objwriter.WriteLine("testing")
objwriter.WriteLine("")
objwriter.Close()

Based on what I had obtained rthus far, I may have to define a variable as a string then append it to my StreamWriter write command?

Dim user_name As String = Environment.UserName

Just trying to now put the two together.. any help would be appreciative..

Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
E_xodus
  • 1
  • 3
  • `Dim objwriter As New System.IO.StreamWriter("\\server\path\" + user_name + ".txt")` – Hackerman Jul 26 '18 at 12:51
  • 2
    To combine path parts together, always use [`Path.Combine()`](https://learn.microsoft.com/en-us/dotnet/api/system.io.path.combine), that is, `IO.Path.Combine("\\server\path", user_name & ".txt")`. It might not be very important in this particular case, but it comes in handy when you have several parts to combine. Also, it helps you avoid checking whether each part of the path ends with a "\" or not. – 41686d6564 stands w. Palestine Jul 26 '18 at 12:58
  • bah, so simple yet my brain could not comprehend.. many thanks – E_xodus Jul 26 '18 at 12:59
  • 1
    Use & for strings and + for Mathematical operations. – CruleD Jul 26 '18 at 17:56

1 Answers1

0

Thanks hackerman - this did the trick..

Dim objwriter As New System.IO.StreamWriter("\\server\path\" + user_name + ".txt")
E_xodus
  • 1
  • 3
  • 1
    Note that the native concatenation operator in VB.NET is the ampersand: `&`. The plus `+` also works, but has some drawbacks in certain cases. For more information see: [The difference between + and & for joining strings in VB.NET](https://stackoverflow.com/a/734631) – Visual Vincent Jul 26 '18 at 14:22