The given path's format is not supported (VB.Net) - vb.net

Below coding are code that I used to rename and store images at temporary files.
Declaration as below :
Dim extension As String = Path.GetExtension(hpf.FileName)
Dim rename As String = Now.ToString(gsUserStation + "ddMMyyHHmmss")
Dim imageRename As String = Path.Combine(rename + extension)
Dim imgUrl As String = Server.MapPath("source") & "\" & Path.Combine(rename + extension)
And code to save :
hpf.SaveAs(Server.MapPath("source") & "\" & imageRename)
This coding working fine but I don't know what happened when I run it sometimes with different code of station, it threw me an error
The given path's format is not supported.
When I do debugging, the variable rename (expectation result : BKI081116120002) became something like B+08:00I0811160002. I don't get it, how come the result of station code BKI became B+08:00I. So that is the one that causing the error to happen.
Any suggestion from you guys? Thank you.

Related

Add a path to a code VB.net / visual basic

how do I add a path to a code where "HERE_HAS_TO_BE_A_PATH" is. When I do, Im getting an error message. The goal is to be able to specific the path where is the final text file saved.
Thanks!
Here is a code:
Dim newFile As IO.StreamWriter = IO.File.CreateText("HERE_HAS_TO_BE_A_PATH")
Dim fix As String
fix = My.Computer.FileSystem.ReadAllText("C:\test.txt")
fix = Replace(fix, ",", ".")
My.Computer.FileSystem.WriteAllText("C:\test.txt", fix, False)
Dim query = From data In IO.File.ReadAllLines("C:\test.txt")
Let name As String = data.Split(" ")(0)
Let x As Decimal = data.Split(" ")(1)
Let y As Decimal = data.Split(" ")(2)
Let z As Decimal = data.Split(" ")(3)
Select name & " " & x & "," & y & "," & z
For i As Integer = 0 To query.Count - 1
newFile.WriteLine(query(i))
Next
newFile.Close()
1) Use a literal string:
The easiest way is replacing "HERE_HAS_TO_BE_A_PATH" with the literal path to desired output target, so overwriting it with "C:\output.txt":
Dim newFile As IO.StreamWriter = IO.File.CreateText("C:\output.txt")
2) Check permissions and read/write file references are correct:
There's a few reasons why you might be having difficulties, if you're trying to read and write into the root C:\ directory you might be having permissions issues.
Also, go line by line to make sure that the input and output files are correct every time you are using one or the other.
3) Make sure the implicit path is correct for non-fully qualified paths:
Next, when you test run the program, it's not actually in the same folder as the project folder, in case you're using a relative path, it's in a subfolder "\bin\debug", so for a project named [ProjectName], it compiles into this folder by default:
C:\path\to\[ProjectName]\bin\Debug\Program.exe
In other words, if you are trying to type in a path name as a string to save the file to and you don't specify the full path name starting from the C:\ drive, like "output.txt" instead of "C:\output.txt", it's saving it here:
C:\path\to\[ProjectName]\bin\Debug\output.txt
To find out exactly what paths it's defaulting to, in .Net Framework you can check against these:
Application.ExecutablePath
Application.StartupPath
4) Get user input via SaveFileDialogue
In addition to a literal string ("C:\output.txt") if you want the user to provide input, since it looks like you're using .Net Framework (as opposed to .Net Core, etc.), the easiest way to set a file name to use in your program is using the built-in SaveFileDialogue object in System.Windows.Forms (like you see whenever you try to save a file with most programs), you can do so really quickly like so:
Dim SFD As New SaveFileDialog
SFD.Filter = "Text Files|*.txt"
SFD.ShowDialog()
' For reuse, storing file path to string
Dim myFilePath As String = SFD.FileName
Dim newFile As IO.StreamWriter = IO.File.CreateText(myFilePath) ' path var
' Do the rest of your code here
newFile.Close()
5) Get user input via console
In case you ever want to get a path in .Net Core, i.e. with a console, the Main process by default accepts a String array called args(), here's a different version that lets the user add a path as the first parameter when running the program, or if one is not provided it asks the user for input:
Console.WriteLine("Hello World!")
Dim myFilePath = ""
If args.Length > 0 Then
myFilePath = args(0)
End If
If myFilePath = "" Then
Console.WriteLine("No file name provided, please input file name:")
While (myFilePath = "")
Console.Write("File and Path: ")
myFilePath = Console.ReadLine()
End While
End If
Dim newFile As IO.StreamWriter = IO.File.CreateText(myFilePath) ' path var
' Do the rest of your code here
newFile.Close()
6) Best practices: Close & Dispose vs. Using Blocks
In order to keep the code as similar to yours as possible, I tried to change only the pieces that needed changing. Vikyath Rao and Mary respectively pointed out a simplified way to declare it as well as a common best practice.
For more information, check out these helpful explanations:
Can any one explain why StreamWriter is an Unmanaged Resource. and
Should I call Close() or Dispose() for stream objects?
In summary, although streams are managed and should garbage collect automatically, due to working with the file system unmanaged resources get involved, which is the primary reason why it's a good idea to manually dispose of the object. Your ".close()" does this. Overrides for both the StreamReader and StreamWriter classes call the ".dispose()" method, however it is still common practice to use a Using .. End Using block to avoid "running with scissors" as Enigmativity puts it in his post, in other words it makes sure that you don't go off somewhere else in the program and forget to dispose of the open filestream.
Within your program, you could simply replace the "Dim newFile As IO.StreamWriter = IO.File.CreateText("C:\output.txt")" and "newFile.close()" lines with the opening and closing statements for the Using block while using the simplified syntax, like so:
'Dim newFile As IO.StreamWriter = IO.File.CreateText(myFilePath) ' old
Using newFile As New IO.StreamWriter(myFilePath) ' new
Dim fix As String = "Text from somewhere!"
newFile.WriteLine(fix)
' other similar operations here
End Using ' new -- ensures disposal
'newFile.Close() ' old
You can write that in this way. The stream writer automatically creates the file.
Dim newFile As New StreamWriter(HERE_HAS_TO_BE_A_PATH)
PS: I cannot mention all these in the comment section as I have reputations less than 50, so I wrote my answer. Please feel free to tell me if its wrong
regards,
vikyath

how do I use a document using debug folder (vb.net)

I am trying to show a document (called zzz.txt so it appears at the bottom) in a text box, and I have put it in the debug folder (TextViewerthingy > obj > Debug) and have used CurDir() & "\zzz.txt" for the location, which apparently is not correct. I have used this correctly with other projects
Dim filename As String = CurDir() & "\zzz.txt"
Dim ObjReader As New System.IO.StreamReader(filename)
gives me an error saying the file is not there. This is the location, what is it that I'm doing wrong in this case?
C:\Users\Notshowingmyname\source\repos\TextViewerthingy\TextViewerthingy\bin\Debug
Try this one :
Imports System.IO
Dim filename as string = Directory.GetCurrentDirectory() + "\zzz.txt"
Or second alternative :
filename = My.Computer.FileSystem.CurrentDirectory + "\zzz.txt"
Make sure file name and extensions are correct.

Compiling VB Code With CodeDom

Read up on it, couldn't find anything that worked for me.
Basically, I have a file called SourceCode.vb in my resources.
I'm trying to use:
Dim objCodeCompiler As System.CodeDom.Compiler.ICodeCompiler = New VBCodeProvider().CreateCompiler
Dim objCompilerParameters As New System.CodeDom.Compiler.CompilerParameters()
objCompilerParameters.ReferencedAssemblies.Add("System.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Windows.Forms.dll")
objCompilerParameters.ReferencedAssemblies.Add("Microsoft.VisualBasic.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Drawing.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Data.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Deployment.dll")
objCompilerParameters.ReferencedAssemblies.Add("System.Xml.dll")
objCompilerParameters.GenerateExecutable = True
objCompilerParameters.GenerateInMemory = False
objCompilerParameters.CompilerOptions = "/target:winexe"
objCompilerParameters.OutputAssembly = "C:\"
Dim strCode As String = My.Resources.SourceCode.ToString
Dim objCompileResults As System.CodeDom.Compiler.CompilerResults = objCodeCompiler.CompileAssemblyFromSource(objCompilerParameters, strCode)
If objCompileResults.Errors.HasErrors Then
MsgBox("Error: Line>" & objCompileResults.Errors(0).Line.ToString & ", " & objCompileResults.Errors(0).ErrorText)
Exit Sub
End If
I need it to compile the code and make the file and place it in C:\ - For some reason its not working. Error is:
error: line>0, no input sources specified
Any ideas? Thanks in advance.
Edit: Problem was that I needed to add an actual name for the file after the output. Thanks for the help Hans.
It's actually because you are setting OutputAssembly to a location when it expects an assembly name. It should be:
objCompilerParameters.OutputAssembly = "AssemblyName.exe"
If you want to set the location of the output assembly, add it to your compiler options.
objCompilerParameters.CompilerOptions = "/target:winexe /out:C:\\AssemblyName.exe"
Although, I believe if you want to write to the C: drive, you will need to run your program as administrator.

VB.net use string in Directory Path?

I apologise for my lack of basic VB.net knowledge but I'm looking to use the equivalent of %systemdrive% to find the drive containing Windows to check for an existing directory in VB.net - so I have the below.
Dim systemPath As String = Mid(Environment.GetFolderPath(Environment.SpecialFolder.System), 1, 3)
If Not Directory.Exists("'systemPath'\MyFolder") Then
Directory.CreateDirectory("'systemPath'\MyFolder")
End If
Can someone help with using the systemPath string in the directory query? Thank you.
Well you should write
Dim systemPath As String = Mid(Environment.GetFolderPath(Environment.SpecialFolder.System), 1, 3)
If Not Directory.Exists(Path.Combine(systemPath, "MyFolder")) Then
Directory.CreateDirectory(Path.Combine(systemPath, "MyFolder"))
End If
You could get the environment variable called %SYSTEMDRIVE% with Environment.GetEnvironmentVariable, but then the results obtained should be manually combined with current directory separator char ("\") because I have not found any way to convince Path.Combine to build a valid path with only the system drive (I.E. C: )
Dim sysDrive = Environment.GetEnvironmentVariable("SystemDrive")
Dim myPath = sysDrive & Path.DirectorySeparatorChar & "MyFolder"
IO.Path has methods that should be used IMHO
Dim sysDrive As String = Environment.GetEnvironmentVariable("SystemDrive") & IO.Path.DirectorySeparatorChar
Dim myPath As String = IO.Path.Combine(sysDrive, "FolderName")

Issue with an LPR Command in VB

I am creating a VB app which will "move" xls reports from a directory to a ReportSafe app. I am also working in an existing VB app which does just that, so I am using it for reference.
It isn't as simple as moving files from one directory to another, because ReportSafe requires an lpr command to tell it (ReportSafe) which file to pick up.
Here is what I have so far:
Imports System.IO
Module Module1
Sub Main()
''Declarations
Dim Files As ArrayList = New ArrayList()
Dim FileName As String
''Write All Files in *directory* to ReportSafe
Files.Clear()
Files.AddRange(Directory.GetFiles(*directory*))
For Each FileName In Files
Dim RPname As String
Dim RealName As String
RPname = FileName.ToString
RealName = "/"
RealName = RealName & RPname.Remove(0, 34)
Dim a As New Process
a.StartInfo.FileName = "C:\Windows\system32\lpr.exe"
a.StartInfo.Arguments = "-S*ServerName* -Plp -J" & Chr(34) & RealName & Chr(34) & " " & Chr(34) & RPname & Chr(34)
a.StartInfo.UseShellExecute = False
Next
End Sub
End Module
The whole lpr command/arguments are throwing me for a loop. I'm not sure if my question is specific to ReportSafe, and if that's the case, I may be out of luck here. I have pulled this code from the already existing app which moves reports to ReportSafe, and adjusted for my own use, but no luck so far.
FYI, I had to turn on LPR Monitor services to obtain to the lpr.exe
Questions:
What are the proper arguments to pass through to this lpr command?
Is there a problem with the logic that is causing the issue?
I continued to tinker and look at my reference code and discovered some flaws in logic:
For one, the report name I was passing did not include the complete file path.
Another thing is that I never started the process with a.Start(). Rookie mistakes for sure... haha