VB.NET System32 Path FileNotFoundException - vb.net

I have the following code :
Imports System.Management
Module Module1
Private MicrosoftProcs As New List(Of String)
Private Sub FindMicrosoftProcs()
Dim searcher As New ManagementObjectSearcher("SELECT * FROM Win32_Process")
For Each p2 As ManagementObject In searcher.Get()
If p2("Name") <> "System" Or p2("Name") <> "System Idle Process" Or p2("Name") <> Process.GetCurrentProcess.ProcessName & ".exe" Then
Dim x As String = p2("ExecutablePath")
If Not x Is Nothing Then
If x.Length > 2 Then
Dim fvi As System.Diagnostics.FileVersionInfo = System.Diagnostics.FileVersionInfo.GetVersionInfo(p2("ExecutablePath").ToString)
Dim sDescription As String = fvi.CompanyName & "/" & fvi.LegalCopyright & "/" & fvi.LegalTrademarks & "/" & fvi.ProductName & "/" & fvi.FileDescription & "/"
If sDescription.ToLower.Contains("microsoft") Then
MicrosoftProcs.Add(p2("ExecutablePath"))
Debug.WriteLine("Microsoft process : " & p2("ExecutablePath"))
End If
End If
End If
End If
Next
End Sub
End Module
I am working on 64bit Windows but the code is compiled for 32bit Windows (for compatibility). If I run the code compiled for 64bit , i have not problems with the code, but if I run it compiled for 32bit I get the FileNotFoundException :
A first chance exception of type 'System.IO.FileNotFoundException' occurred in System.dll
System.IO.FileNotFoundException: C:\Windows\system32\csrss.exe
at System.Diagnostics.FileVersionInfo.GetVersionInfo(String fileName)
at WindowsApplication1.Form1.Button1_Click(Object sender, EventArgs e) in C:\Users\Maximus\Documents\Visual Studio 2010\Projects\rupe\rupe\Form1.vb:line 81
And I don't know how to fix it. Can you help me please ? Thanks in advance.

I cannot seem to find an exact answer to this but I am quite sure that the problem is that 32bit processes do not have permission to access the modules of a 64 bit process. This is why you have no problems with your 64bit app but the 32bit app doesn't like certain processes. The best resource I could find for this was another SO question which you can read here: System.ArgumentException and System.ComponentModel.Win32Exception when getting process information.
That being said there doesn't appear to be a way to get the file information for these 64bit processes when you are running a 32bit app. If you absolutely need this information you have no choice but to build your app as 64bit. If you don't really need this information and want to just carry on with the processes that you have access to in a 32bit app you can try something like this:
Private Sub FindMicrosoftProcs()
Try
Dim searcher As New ManagementObjectSearcher("SELECT * FROM Win32_Process")
For Each p2 As ManagementObject In searcher.Get()
If p2("Name") <> "System" Or p2("Name") <> "System Idle Process" Or p2("Name") <> Process.GetCurrentProcess.ProcessName & ".exe" Then
Dim x As String = p2("ExecutablePath")
If Not x Is Nothing Then
If x.Length > 2 Then
Dim fvi As System.Diagnostics.FileVersionInfo
Try
fvi = System.Diagnostics.FileVersionInfo.GetVersionInfo(p2("ExecutablePath").ToString)
Dim sDescription As String = fvi.CompanyName & "/" & fvi.LegalCopyright & "/" & fvi.LegalTrademarks & "/" & fvi.ProductName & "/" & fvi.FileDescription & "/"
If sDescription.ToLower.Contains("microsoft") Then
MicrosoftProcs.Add(p2("ExecutablePath"))
Debug.WriteLine("Microsoft process : " & p2("ExecutablePath"))
End If
Catch ex As Exception
nSkipped += 1
End Try
End If
End If
End If
Next
MessageBox.Show("Found " & MicrosoftProcs.Count & " and skipped " & nSkipped & " files.")
Catch ex As Exception
MessageBox.Show("Error: " & ex.Message)
End Try
End Sub

Related

Timer to skip to connect to next computer in for each loop while connecting remotely using RegistryKey.OpenRemoteBaseKey

I built a tool (with Visual Studio 2015 Express - Visual Basic) that will check the mcafee dat version and date from the registry on computers input either manually, in a text file, or selected from active directory. The tool works it successfully returned all the information for 714 out of 970 computers/laptops. The majority of the failures were either because they could not be resolved in DNS or weren't pingable and the tools identifies those and successfully logs them. It took a little over 15 minutes for the tool to retrieve the information and log it in a spreadsheet. The issue is that on 19 of the failures I got one of the two following errors and those 19 took the majority of the 15 minutes for the tool get and log all the information:
Attempted to perform an unauthorized operation
The network path was not found
Is there a way of using a timer so that the program will attempt to connect to the registry at this point... rk1 = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, strComputer, RegistryView.Registry64) and then after a certain amount of time stop and move to the next computer in the for each loop? I have only been programming for a little over a year and I have learned exclusively through trial/error and google so please have patience with me as I am not a seasoned programmer. Here is the code:
The program works well my objective here is to improve it by making it skip to the next computer when it hangs for an extended period of time. I have filtered out the computers that can't be resolved in DNS or aren't pingable.
For Each sel In picker.SelectedObjects
Try
If HostIsResolvable(sel.Name) Then
Try
reply = ping.Send(sel.Name, 1)
If reply.Status = IPStatus.Success Then
IPAddr = reply.Address.ToString()
Try
comsys(sel.Name)
Dim rk1 As RegistryKey
Dim rk2 As RegistryKey
rk1 = RegistryKey.OpenRemoteBaseKey
(RegistryHive.LocalMachine, sel.Name,
RegistryView.Registry64)
rk2 = rk1.OpenSubKey
("SOFTWARE\Wow6432Node\McAfee\AVEngine")
mAV = rk2.GetValue("AVDatVersion").ToString
mAD = rk2.GetValue("AVDatDate").ToString
objExcel.Cells(y, 1) = sel.Name
objExcel.Cells(y, 2) = IPAddr
objExcel.Cells(y, 3) = commodel
objExcel.Cells(y, 4) = comuser
objExcel.Cells(y, 5) = "DAT Version Number: " & mAV
objExcel.Cells(y, 6) = "DAT Date: " & mAD
y = y + 1
Catch ex As Exception
My.Computer.FileSystem.WriteAllText(Dell
& "\McAfeeDATeNumFailed.txt", sel.Name & "-Unable to
connect. Make sure this computer is on the network,
has remote administration enabled, and that both
computers are running the remote registry service.
Error message: " & ex.Message & vbCrLf, True)
End Try
Else
My.Computer.FileSystem.WriteAllText(Dell
& "\McAfeeDATeNumFailed.txt", sel.Name & " is not
pingable! " & vbCrLf, True)
End If
Catch ex As Exception
My.Computer.FileSystem.WriteAllText(Dell
& "\McAfeeDATeNumFailed.txt", sel.Name & "Ping error:
Unable to connect. Make sure this computer is on the
network, has remote administration enabled, and that
both computers are running the remote registry
service. Error message: " & ex.Message & vbCrLf, True)
End Try
Else
My.Computer.FileSystem.WriteAllText(Dell
& "\McAfeeDATeNumFailed.txt", sel.Name & " could not be
resolved in DNS! " & vbCrLf, True)
End If
Catch ex As Exception
My.Computer.FileSystem.WriteAllText(Dell
& "\McAfeeDATeNumFailed.txt", sel.Name & "DNS error: Unable to
connect. Make sure this computer is on the network, has remote
administration enabled, andd that both computers are running the
remote registry service. Error message: " & ex.Message &
vbCrLf, True)
End Try
sel = Nothing
Next
You need to put your request in another thread. This thread can be aborted.
Sub Main()
Dim thrd As New Thread(AddressOf endlessLoop) 'thread with your sub
thrd.Start() 'Start thread
thrd.Join(1000) 'Block until completion or timeout
If thrd.IsAlive Then
thrd.Abort() 'abort thread
Else
'thread finished already
End If
End Sub
Sub endlessLoop()
Try
While True
'Your Code
End While
Catch ex As ThreadAbortException
'Your code when thread is killed
End Try
End Sub
Hope this helps.
'***** EDIT ***
Your code could look like this (I didn't checked if there are any variables to pass in Sub)
For Each sel In picker.SelectedObjects
Try
If HostIsResolvable(sel.Name) Then
Try
reply = ping.Send(sel.Name, 1)
If reply.Status = IPStatus.Success Then
IPAddr = reply.Address.ToString()
call timerThread 'New
Else
My.Computer.FileSystem.WriteAllText(Dell
& "\McAfeeDATeNumFailed.txt", sel.Name & " is not
pingable! " & vbCrLf, True)
End If
Catch ex As Exception
My.Computer.FileSystem.WriteAllText(Dell
& "\McAfeeDATeNumFailed.txt", sel.Name & "Ping error:
Unable to connect. Make sure this computer is on the
network, has remote administration enabled, and that
both computers are running the remote registry
service. Error message: " & ex.Message & vbCrLf, True)
End Try
Else
My.Computer.FileSystem.WriteAllText(Dell
& "\McAfeeDATeNumFailed.txt", sel.Name & " could not be
resolved in DNS! " & vbCrLf, True)
End If
Catch ex As Exception
My.Computer.FileSystem.WriteAllText(Dell
& "\McAfeeDATeNumFailed.txt", sel.Name & "DNS error: Unable to
connect. Make sure this computer is on the network, has remote
administration enabled, andd that both computers are running the
remote registry service. Error message: " & ex.Message &
vbCrLf, True)
End Try
sel = Nothing
Next
Sub timerThread()
Dim thrd As New Thread(AddressOf registryRequest) 'thread with your sub
thrd.Start() 'Start thread
thrd.Join(15000) 'Block until completion or timeout (15 seconds)
If thrd.IsAlive Then
thrd.Abort() 'abort thread
Else
'thread finished already
End If
End Sub
Sub registryRequest()
Try
comsys(sel.Name)
Dim rk1 As RegistryKey
Dim rk2 As RegistryKey
rk1 = RegistryKey.OpenRemoteBaseKey
(RegistryHive.LocalMachine, sel.Name,
RegistryView.Registry64)
rk2 = rk1.OpenSubKey
("SOFTWARE\Wow6432Node\McAfee\AVEngine")
mAV = rk2.GetValue("AVDatVersion").ToString
mAD = rk2.GetValue("AVDatDate").ToString
objExcel.Cells(y, 1) = sel.Name
objExcel.Cells(y, 2) = IPAddr
objExcel.Cells(y, 3) = commodel
objExcel.Cells(y, 4) = comuser
objExcel.Cells(y, 5) = "DAT Version Number: " & mAV
objExcel.Cells(y, 6) = "DAT Date: " & mAD
y = y + 1
Catch ex As ThreadAbortException
My.Computer.FileSystem.WriteAllText(Dell
& "\McAfeeDATeNumFailed.txt", sel.Name & "-Unable to
connect. Make sure this computer is on the network,
has remote administration enabled, and that both
computers are running the remote registry service.
Error message: " & ex.Message & vbCrLf, True)
End Try
End Sub
This works great but I am sure it can be improved so please respond with suggestions if you have them. Here is the code:
Try
Dim source1 As New CancellationTokenSource
Dim token As CancellationToken = source1.Token
Dim T20 As Task = Task.Factory.StartNew(Function() getping((sel.Name), token))
T20.Wait(30)
If T20.Status = TaskStatus.Running Then
source1.Cancel()
My.Computer.FileSystem.WriteAllText(Dell & "\McAfeeDATeNumFailed.txt", sel.Name & " Ping timed out. The task was disposed of at " & ex_time & "." & vbCrLf & vbCrLf, True)
End If
Dim source2 As New CancellationTokenSource
Dim token2 As CancellationToken = source2.Token
Dim T21 As Task = Task.Factory.StartNew(Function() comsys((sel.Name), token2))
T21.Wait(500)
If T21.Status = TaskStatus.Running Then
source2.Cancel()
My.Computer.FileSystem.WriteAllText(Dell & "\McAfeeDATeNumFailed.txt", sel.Name & " RPC error. The task was disposed of at " & ex_time & "." & vbCrLf & vbCrLf, True)
End If
Dim source3 As New CancellationTokenSource
Dim token3 As CancellationToken = source3.Token
Dim T22 As Task = Task.Factory.StartNew(Function() getregvalues((sel.Name), token3))
T22.Wait(600)
If T22.Status = TaskStatus.Running Then
source3.Cancel()
My.Computer.FileSystem.WriteAllText(Dell & "\McAfeeDATeNumFailed.txt", sel.Name & " Error retrieving registry value. The task was disposed of at " & ex_time & "." & vbCrLf & vbCrLf, True)
End If
IPAddr = reply.Address.ToString()
objExcel.Cells(y, 1) = sel.Name
objExcel.Cells(y, 2) = IPAddr
objExcel.Cells(y, 3) = commode
objExcel.Cells(y, 4) = comuser
objExcel.Cells(y, 5) = "DAT Version Number: " & mAV
objExcel.Cells(y, 6) = "DAT Date: " & mAD
y = y + 1
IPAddr = Nothing
reply = Nothing
commodel = Nothing
comuser = Nothing
sel = Nothing
Thread.Sleep(10)
Catch ex As Exception
End Try
I will try that and time it both ways. I added a continue for here and it cut it from 6 and a half minutes down to 3 and a half minutes (if it wasn't pingable then move on to the next computer instead of running the other 2 tasks).
If T20.Status = TaskStatus.Running Then
source1.Cancel()
Continue For
End If
I started to change the wait to a loop and I remembered that it takes that amount of time to successfully retrieve the remote information and get it into excel without missing data in the excel spreadsheet. For example I dropped the time to 10 ms and some of the computers didn't respond to the ping fast enough so that computer and it's information wasn't added to the spreadsheet. Likewise, I reduced the ms on the registry task and the registry information for that computer was missing in the spreadsheet.

Getting BC31019 excepetion while compiling vb.net at runtime on Windows 10

we are generating a mass of documents very dynamically. Therefore we concatenate source code and build a dll at runtime. This is running since windows XP.
Now we are in tests of windows 10 and it fails compiling this dll with the error "BC31019: Unable to write to output file 'C:\Users[name]AppData\Local\Temp\xyz.dll': The specified image file did not contain a resource section"
For testing purposes we remove all generated source code and replace it by a rudimental class with only one function (throwing an exception with specified text) and no referenced assemblies.
This is also running on all machines except windows 10. Same error.
Can anybody guess why?
This is the rudimental method
Public Sub Compile()
Dim lSourceCode = "Namespace DynamicOutput" & vbCrLf &
" Public Class Template" & vbCrLf &
" Sub New()" & vbCrLf &
" End Sub" & vbCrLf &
" Public Sub Generate(ByVal spoolJob As Object, ByVal print As Object)" & vbCrLf &
" Throw New System.Exception(""Generate reached"")" & vbCrLf &
" End Sub" & vbCrLf &
"" & vbCrLf &
" End Class" & vbCrLf &
"End Namespace"
Dim lParams As CodeDom.Compiler.CompilerParameters = New CodeDom.Compiler.CompilerParameters
lParams.CompilerOptions = "/target:library /rootnamespace:CompanyName /d:TRACE=TRUE /optimize "
lParams.IncludeDebugInformation = True
lParams.GenerateExecutable = False
lParams.TreatWarningsAsErrors = False
lParams.GenerateInMemory = True
Dim lProviderOptions As New Dictionary(Of String, String) From {{"CompilerVersion", "v4.0"}}
Dim lResult As CodeDom.Compiler.CompilerResults = Nothing
Using provider As New VBCodeProvider(lProviderOptions)
lResult = provider.CompileAssemblyFromSource(lParams, lSourceCode)
End Using
' ... check for errors
Dim lInstance As Object = lResult.CompiledAssembly.CreateInstance("CompanyName.DynamicOutput.Template")
lInstance.GetType.GetMethod("Generate").Invoke(lInstance, New Object() {Me.SpoolJob, Me.Print})
End Sub

Visual basic : Generic GDI+ error when saving file

When I executed my program I created in visual basic. I got a GDI+ error when I tried to save an image from a picturebox.
If I run it on the PC, where I created the program(windows 10), I don't have any problems. When I run it on 2 different windows 7 PC's, I got the error.
The mapped networkdrive is the same ( Z:\ ) and writeable.
Here is the code:
Private Sub SaveImage(ByVal pathToSaveTo As String)
Try
Using bmp As New Bitmap(Picimage.Image)
bmp.Save(pathToSaveTo, Drawing.Imaging.ImageFormat.Jpeg)
End Using
Catch ex As Exception
MessageBox.Show("An error occurred:" & vbCrLf & vbCrLf & _
ex.Message, "Error Saving Image File", _
MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End Try
End Sub
The button to start the action
Private Sub Button2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim dt As String = My.Computer.FileSystem.SpecialDirectories.Desktop
Dim testOutput As String
testOutput = "Z:\" & naam & " " & Now.ToString("HH/mm/ss") & ".jpg"
SaveImage(testOutput)
nr.Focus()
End Sub
GDI is complaining about the filename you're using.
Here's the problem: testOutput = "Z:\" & naam & " " & Now.ToString("HH/mm/ss") & ".jpg"
You're generating a filename with slashes in the path. If those are meant to be directory names (a directory for each hour, minute and second respectively) then those directories need to ex that won't work as GDI will not create missing directories along a path for you. If the slashes are meant to be in the filename itself then it also won't work as slashes are not a valid filename character.
Change the slashes to underscores or hyphens or other characters allowed in filenames:
testOutput = "Z:\" & naam & " " & Now.ToString("HH_mm_ss") & ".jpg"

Executing msg.exe from Visual Basic application

I am trying to take text fields for old hostname, new hostname, username, and password and remotely change computer names. That part is working fantastic. It was all great until my manager saw it in action, since we have a policy against downloading and using freeware.
It's not freeware if I made it. Unfortunately, he sent it to my director, and know my director knows I know a little bit about Visual Basic, so he wants to loop the names from a CSV file, change the name, and send a message to the end user instructing them to save their files and reboot.
Unfortunately, net send has gone the way of XP since Vista. However, from Vista - Win8.1, there's a utility called msg.exe in C:\Windows\System32. In order to use it, the target computer has to have the registry value AllowRemoteRPC in HKLM\SYSTEM\CurrentControlSet\Control\Terminal Services set to 1.
So here's what the app does:
Reads the DWORD key AllowRemoteRPC and stores it to a variable (MyVal), changes the key to 1, attempts to send the message alerting the user they need to restart, changes the key back to MyVal, and then executes netdom renamecomputer and renames the PC. Everything works perfectly EXCEPT sending the message. I can open up a command prompt and type:
msg /server:hostname * /v /time:3600 "my message here
And it works perfectly (after manually editing the registry key to the needed value).
However, running it from VB doesn't work. Here's what I've tried:
"msg /server:" & hostname & " * /v /time:3600 ""my message here"""
"cmd.exe /D /c msg /server:" & hostname & " * /v /time:3600 ""my message here"""
Neither seems to work. I know the registry value is being changed. I put message boxes after each step in my and refreshed the regedit to actually see the value of the DWORD key, and it is changing. Everything APPEARS to be going smoothly, the message is just not getting sent.
I do have these commands running as arguments to a function I created in order to create a process so I could output the streamreader to a listbox.
Here's my code. Please keep in mind, I'm barely over 2 months into learning visual basic, so it's probably not the prettiest code out there:
Imports System
Imports System.IO
Imports System.Diagnostics
Imports System.Security.Permissions
Imports Microsoft.Win32
Public Class applicationMain
Private Sub btnExecute_Click(sender As Object, e As EventArgs) Handles btnExecute.Click
Dim oldPC As String = txtOldPC.Text
Dim newPC As String = txtNewPC.Text
Dim username As String = txtUsername.Text
Dim password As String = txtPassword.Text
If oldPC <> "" And newPC <> "" And username <> "" And password <> "" Then
Dim MyReg As Microsoft.Win32.RegistryKey = Microsoft.Win32.RegistryKey.OpenRemoteBaseKey(Microsoft.Win32.RegistryHive.LocalMachine, oldPC)
Dim MyRegKey As Microsoft.Win32.RegistryKey
Dim MyVal As String
lbOutput.Items.Clear()
MyRegKey = MyReg.OpenSubKey("System\CurrentControlSet\Control\Terminal Server")
MyVal = MyRegKey.GetValue("AllowRemoteRPC", RegistryValueKind.DWord)
MyRegKey.Close()
lbOutput.Items.Add("Processing registry changes...")
Try
MyRegKey = MyReg.OpenSubKey("System\CurrentControlSet\Control\Terminal Server", True)
MyRegKey.SetValue("AllowRemoteRPC", &H1, RegistryValueKind.DWord)
Catch ex As Exception
MessageBox.Show("An Error Has Occured:" & vbCrLf & vbCrLf & ex.ToString())
lbOutput.Items.Add("")
lbOutput.Items.Add("ABORTED!")
Exit Sub
End Try
lbOutput.Items.Add("Success!")
lbOutput.Items.Add("Sending message to user:")
Try
ExecuteCommand("cmd.exe", "/D /c msg /SERVER:" & oldPC & ".na.int.grp * /v /TIME:3600 ""Changes have been made by IS to your computer that require a restart. Please save your files and restart your computer to avoid service interruption.""")
Catch ex As Exception
MessageBox.Show("An Error Has Occured:" & vbCrLf & vbCrLf & ex.ToString())
lbOutput.Items.Add("")
lbOutput.Items.Add("ABORTED!")
MyRegKey = MyReg.OpenSubKey("System\CurrentControlSet\Control\Terminal Server", True)
MyRegKey.SetValue("AllowRemoteRPC", MyVal, RegistryValueKind.DWord)
Exit Sub
End Try
lbOutput.Items.Add(" Message: ""Changes have been made by IS to your computer that require a restart. Please save your files and restart your computer to avoid service interruption."" ")
lbOutput.Items.Add("Reverting registry changes...")
Try
MyRegKey = MyReg.OpenSubKey("System\CurrentControlSet\Control\Terminal Server", True)
MyRegKey.SetValue("AllowRemoteRPC", MyVal, RegistryValueKind.DWord)
Catch ex As Exception
MessageBox.Show("An Error Has Occured:" & vbCrLf & vbCrLf & ex.ToString())
lbOutput.Items.Add("")
lbOutput.Items.Add("ABORTED!")
Exit Sub
End Try
Try
ExecuteCommand("netdom", "renamecomputer " & oldPC & " /newname:" & newPC & " /userD:na\" & username & " /passwordd:" & password & " /usero:na\" & username & " /passwordo:" & password & " /Force")
Catch ex As Exception
MessageBox.Show("An Error Has Occured:" & vbCrLf & vbCrLf & ex.ToString())
lbOutput.Items.Add("")
lbOutput.Items.Add("ABORTED!")
Exit Sub
End Try
lbOutput.Items.Add("Success!")
lbOutput.Items.Add("")
lbOutput.Items.Add("Rename successful for " & oldPC & "!")
lbOutput.Items.Add("******************************************************************")
lbOutput.Items.Add("")
End If
End Sub
Private Function ExecuteCommand(ByVal cmd As String, ByVal arguments As String)
Dim cmdProcess As New Process()
Dim cmdProcessStartInfo As New ProcessStartInfo()
Dim cmdStreamReader As IO.StreamReader
Dim output As String
cmdProcessStartInfo.UseShellExecute = False
cmdProcessStartInfo.CreateNoWindow = True
cmdProcessStartInfo.RedirectStandardOutput = True
cmdProcessStartInfo.FileName = cmd
cmdProcessStartInfo.Arguments = arguments
cmdProcess.StartInfo = cmdProcessStartInfo
cmdProcess.Start()
cmdStreamReader = cmdProcess.StandardOutput
Do While cmdStreamReader.EndOfStream = False
output = cmdStreamReader.ReadLine()
lbOutput.SelectedIndex = lbOutput.Items.Count - 1
lbOutput.Items.Add(output)
Loop
cmdProcess.WaitForExit()
cmdProcess.Close()
Return vbNull
End Function
End Class
What do you know. There's actually nothing wrong with my code at all. While trying to play around with the paths variable, I decided "Fuhgeddaboudit, I'll just add the executable to the project!". Right clicked the project, Add -> Existing Item. Selected Executable as the type, and went to C:\Windows\System32 and, get this now, msg.exe wasn't there. At all. Opened Explorer and went to System32, msg.exe was there. For whatever reason, Visual Studio cannot see the program at all. Which is in and of itself weird.
So I copied msg.exe to my desktop, added it to source, the program works like a charm now.

Shell in .Net displaying file not found

Folks,
I was using
Shell("LPR -P " & IP & " -S " & IP & "c:\label.txt", AppWinStyle.Hide)
in my code earlier in my code to send print to printer. suddenlt it stopped working. i started getting file not found error. then i chanegd my code to below, but still no show. now i an getting the following error
System.ComponentModel.Win32Exception was caught
ErrorCode=-2147467259 Message=The system cannot find the file
specified NativeErrorCode=2 Source=System StackTrace: at
System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo
startInfo) at System.Diagnostics.Process.Start() at
xxxxxx.LPRProcess(String pstrFilePath, String pstrQueue, String
pstrPrinter) in I:\Visual Studio 2010\Projects\xxxxxx\ScanInSn.vb:line
201 InnerException:
New code
Private Function LPRProcess(ByVal pstrFilePath As String, ByVal pstrQueue As String, ByVal pstrPrinter As String)
Dim prcLprInfo As New ProcessStartInfo
prcLprInfo.FileName = "Lpr"
prcLprInfo.CreateNoWindow = True
prcLprInfo.WindowStyle = ProcessWindowStyle.Hidden
prcLprInfo.UseShellExecute = False
prcLprInfo.RedirectStandardOutput = True
prcLprInfo.Arguments = "-S " & pstrPrinter & " -P " & pstrQueue & " """ & pstrFilePath & """"
Dim prcLpr As New Process
Dim strOutput As String
Try
'Stage = "Run Process.Start( )"
prcLpr.StartInfo = prcLprInfo
prcLpr.Start()
strOutput = prcLpr.StandardOutput.ReadToEnd()
'Stage = "Process started, wait for it to exit"
If Not prcLpr.HasExited Then prcLpr.WaitForExit()
Catch ex As Exception
Throw New Exception("Error running LPR process: " & ex.Message)
Finally
prcLpr.Close()
prcLpr.Dispose()
End Try
If strOutput.Length > 0 Then
Throw New Exception("LPR ERROR: " & strOutput)
End If
End Function
Any ideas? (using .net 4.0)
Resolved the issue by changing settings in Visual Studio Project Prpperties.
Visual Studio > project > properties > Compile > Target CUP.
Changes the Settings to "AnyCPU".
It was set to 64 bit.
Thank you Tom and Steve for your help..