Strange symbols stopping my batch file running in VB.net - vb.net

I am trying to create and run a batch file from VB.net, then get the output and print it out. But when it runs it is appended by these symbols '´╗┐. Causing this error '´╗┐cd' is not recognized as an internal or external command, operable program or batch file. When I look at the batch file in notepad++ there is no symbol there! What is happening! Thanks James.
Code:
Dim path As String = Directory.GetCurrentDirectory()
Dim command As String = "cd " & path & " & " & argument
MsgBox(command)
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter(tempFile, False)
file.WriteLine("#ECHO OFF")
file.WriteLine(command)
file.Close()
Dim objProcess As New Process()
Dim SROutput As System.IO.StreamReader
With objProcess.StartInfo
.FileName = tempFile
.RedirectStandardOutput = True
.UseShellExecute = False
.Arguments = ""
End With
objProcess.Start()
SROutput = objProcess.StandardOutput
Do While SROutput.Peek <> -1
'MessageBox.Show(SROutput.ReadLine)
rtbOutput.Text = rtbOutput.Text & SROutput.ReadLine & vbNewLine
Loop
objProcess.Dispose()
'Process.Start(tempFile)
rtbOutput.Text = rtbOutput.Text & message & vbNewLine

That's a Byte Order Mark.
It means the OpenTextFileWriter() method is using a different encoding than you expect. You can fix the problem by using OpenTextFileWriter() overload that allows you pick an encoding like ASCII with no byte order mark or use the encoding with the byte order mark that matches what the DOS subsystem is expecting.

Solved, Im not entirely sure what was happening when it was writing the file, but I have changed it to this
Using writer As StreamWriter = New StreamWriter(tempFile)
writer.Write(command)
End Using
and its now running fine!. Thanks for any time spent on this and feel free to post an explination as to why this was happening.

Related

VBA FileExists and Sharepoint

I'm running into issues trying to pull info from files stored in Sharepoint.
Namely, FileExists isn't working and Overwrite file doesn't seem to be working either.
There was a discussion here, but few answers -> posting this question again in hopes some things have changed
My code runs like this:
strFileExists = Dir(Filepath & Filename)
And returns: File path not found -> I checked the path and even opened a file and recorded the macro to make sure it was the same file path without issue, but it appears DIR() is the issue.
The business dept I'm working with is entirely switching over to Sharepoint so hoping there's a straightforward solution without setting up network shares or doing C/personal/OneDrive things
You can navigate and look for files on OneDrive like this
Sub check_File_Exists()
Dim path As String
Dim strType As String
Dim file As Variant
Dim yourFile As String
'replace uname with your user name
path = "C:\Users\uname\OneDrive\"
strType = "*txt"
yourFile = "test.txt"
file = Dir(path & strType)
Do While (file <> "")
If file = yourFile Then
Debug.Print ("File: " & file & " found!")
Exit Do
End If
file = Dir
Loop
End Sub
Hope it helps

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.

Compile a visual studio solution programmatically

I have a requirement of programmatically compiling a solution. I cannot directly give the path of MSBuild because it differs between 2013 and earlier versions.
I am sharing my code below -
Using exeprocess As New System.Diagnostics.Process
exeprocess.StartInfo.FileName = "cmd"
exeprocess.StartInfo.CreateNoWindow = True
exeprocess.StartInfo.UseShellExecute = False
exeprocess.StartInfo.RedirectStandardInput = True
exeprocess.StartInfo.RedirectStandardOutput = True
exeprocess.Start()
Dim sw As StreamWriter = exeprocess.StandardInput
Dim sr As StreamReader = exeprocess.StandardOutput
sw.WriteLine("PUSHD C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\")
sw.WriteLine("call vcvarsall.bat")
sw.WriteLine("#MSBuild /t:Rebuild" & " /flp1:logfile=" & """" & logFilePath & """;errorsonly" & " " & """" & solutionPath & """")
sr.ReadLine()
While Not sr.EndOfStream()
sr.ReadLine()
End While
End Using
My requirement is to wait until the compilation is over.
The issue is that it hangs at the line "While Not sr.EndOfStream()".
I am unable to understand the reason for the issue. Not sure if this is the right way of ensuring that the compilation is over.
Any help is highly appreciated.
I can't tell what your specific problem is, but a few recommendations:
Don't bother writing to input stream, just generate a simple .bat text file and launch it.
You can use Microsoft.Build.Utilities.ToolLocationHelper to get any of the paths.
You can use Microsoft.Build.Execution.BuildManager to build programmatically.

My visual basic program is creating files improperly and they won't run correctly through other programs

I have a visual basic program that creates files that are necessary for a semiweekly process. These files are a .bas file (for qbasic) and a .lot file (for voxco automation). I can live without the .bas file and simply put it's functionality directly into my program. I do, however, need the .lot file. Normally these files are copied from old files and edited manually. This is, as you can imagine, tedious. However, the files created by my program do not run properly through any means I have of running them. When I compare the manually created files to the automatically created files, the differences are minimal to nonexistent. The encoding doesn't seem to be an issue either. I simply don't know why the files created by my program are not running properly when the files created manually are working fine.
Here is the code that creates the .lot file:
Dim LotText As String
LotText = *removed*
Dim QuLines As String = Nothing
Dim Reader As New StreamReader(LotFilePath & OldStudy & ".LOT")
Dim SLine As String = Nothing
While Not Reader.EndOfStream
SLine = Reader.ReadLine()
If SLine.StartsWith("*QU") Then
QuLines = QuLines & SLine & vbCrLf
End If
End While
LotText = LotText & QuLines
Dim TempPath As String
TempPath = LotFilePath & "BackEnd\" & StudyID & ".LOT"
My.Computer.FileSystem.WriteAllText(TempPath, LotText, 0)
When you say the differences are minimal - what are they exactly!? A single character at the beginning of the file could be making the whole thing fail.
I have had problems in the past with writing vbCrLf to files in this manner; try the following code instead to see if it offers any improvement.
Dim LotText As String = *removed*
' Create a list of strings for the output data
Dim QuLines As New Collections.Generic.List(Of String)
Dim Reader As New StreamReader(Path.Combine(LotFilePath, OldStudy & ".LOT"))
Dim SLine As String = Nothing
While Not Reader.EndOfStream
SLine = Reader.ReadLine()
If SLine.StartsWith("*QU") Then
' This line is desired; add it to our output list
QuLines.Add(SLine)
End If
End While
' Concatenate the existing data and the output; uses the system defined NewLine
LotText &= Environment.NewLine & String.Join(Environment.Newline, QuLines)
Dim TempPath As String = Path.Combine(LotFilePath, "BackEnd", StudyID & ".LOT")
My.Computer.FileSystem.WriteAllText(TempPath, LotText, 0)

Get the output of a shell Command in VB.net

I have a VB.net program in which I call the Shell function. I would like to get the text output that is produced from this code in a file. However, this is not the return value of the executed code so I don't really know how to.
This program is a service but has access to the disk no problem as I already log other information. The whole service has multiple threads so I must also make sure that when the file is written it's not already accessed.
You won't be able to capture the output from Shell.
You will need to change this to a process and you will need to capture the the Standard Output (and possibly Error) streams from the process.
Here is an example:
Dim oProcess As New Process()
Dim oStartInfo As New ProcessStartInfo("ApplicationName.exe", "arguments")
oStartInfo.UseShellExecute = False
oStartInfo.RedirectStandardOutput = True
oProcess.StartInfo = oStartInfo
oProcess.Start()
Dim sOutput As String
Using oStreamReader As System.IO.StreamReader = oProcess.StandardOutput
sOutput = oStreamReader.ReadToEnd()
End Using
Console.WriteLine(sOutput)
To get the standard error:
'Add this next to standard output redirect
oStartInfo.RedirectStandardError = True
'Add this below
Using oStreamReader As System.IO.StreamReader = checkOut.StandardError
sOutput = oStreamReader.ReadToEnd()
End Using
Just pipe the output to a text file?
MyCommand > "c:\file.txt"
Then read the file.
Dim proc As New Process
proc.StartInfo.FileName = "C:\ipconfig.bat"
proc.StartInfo.UseShellExecute = False
proc.StartInfo.RedirectStandardOutput = True
proc.Start()
proc.WaitForExit()
Dim output() As String = proc.StandardOutput.ReadToEnd.Split(CChar(vbLf))
For Each ln As String In output
RichTextBox1.AppendText(ln & vbNewLine)
lstScan.Items.Add(ln & vbNewLine)
Next
=======================================================================
create a batch file in two lines as shown below:
echo off
ipconfig
' make sure you save this batch file as ipconfig.bat or whatever name u decide to pick but make sure u put dot bat at the end of it.