Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsFree MagazinesWhite PapersSubmit Content
Discussion GroupsASP.NETWindows FormsLanguages.NET FrameworkVisual Studio.NET
Articles.NET FrameworkASP.NETToolsWindows Forms
.NET DirectoryOpen Source ProjectsUser GroupsWeb Resources
Related Topics
Visual Basic 6SQL ServerMS AccessOther DB ProductsMS Server ProductsMore Topics ...

.NET Forum / .NET Framework / New Users / November 2006

Tip: Looking for answers? Try searching our database.

Redirecting System.Diagnostics.Process.StandardInput

Thread view: 
Enable EMail Alerts  Start New Thread
Thread rating: 
Dick - 07 Nov 2006 11:55 GMT
The code below uses System.Diagnostics.Process to call Net.exe to delete a
mapped network drive. It works well except when the mapped drive is in use in
which case Net.exe prompts the "user" to confirm the drive should be deleted.
I'm sure I should be able to reply to this question by redirected the
Process's StandardInput but despite hours of trying I can't see how. Is it
possible?

Private Sub UnMapNetworkDrive(ByVal DriveLetter As String)
       Dim _Process As New System.Diagnostics.Process()
       With _Process
           Try
               With .StartInfo
                   .FileName = String.Format("{0}\Net.exe",
System.Environment.GetFolderPath(Environment.SpecialFolder.System))
                   .Arguments = String.Format("use {0}: /delete",
DriveLetter)
                   .CreateNoWindow = True
                   .UseShellExecute = False
                   .RedirectStandardError = True
                   .RedirectStandardOutput = True
               End With
               .Start()
               .WaitForExit()
               Dim _StandardError As String = .StandardError.ReadToEnd
               If Not _StandardError = String.Empty Then Throw New
ApplicationException(_StandardError)
               Dim _StandardOutput As String = .StandardOutput.ReadToEnd
               If Not _StandardOutput.StartsWith(String.Format("{0}: was
deleted successfully.", DriveLetter)) Then Throw New
ApplicationException("The network drive was not unmapped.")
           Finally
               .Close()
           End Try
       End With
   End Sub
Dick - 07 Nov 2006 15:37 GMT
...and perhaps you might also say whether this is the best way to add a
mapped network drive using .net. Or should I call wsh. Or is there a better
way?
Ben Voigt - 07 Nov 2006 22:22 GMT
> ...and perhaps you might also say whether this is the best way to add a
> mapped network drive using .net. Or should I call wsh. Or is there a
> better
> way?

You notably didn't set RedirectStandardInput.

But, here is your better way:
http://pinvoke.net/default.aspx/mpr/WNetAddConnection2.html
Jeffrey Tan[MSFT] - 08 Nov 2006 09:51 GMT
Hi Dick,

Yes, my thought is the same as you to leverage net.exe. However, further
research shows that there is some strange behavior in net.exe which makes
this solution nonapplicable.

To force close the connection, we should input "y" to the net.exe standard
input. So I set RedirectStandardInput proeprty to true and try to send "y"
to the standard input. See the code snippet below:

Private Sub UnMapNetworkDrive(ByVal DriveLetter As String)
       Dim _Process As New System.Diagnostics.Process()
       Dim path As String =
System.Environment.GetFolderPath(Environment.SpecialFolder.System)
       With _Process
           With .StartInfo
               .FileName = String.Format("{0}\Net.exe", path)
               .Arguments = String.Format("use {0} /delete", DriveLetter)
               .CreateNoWindow = True
               .UseShellExecute = False
               .RedirectStandardOutput = True
               .RedirectStandardInput = True
           End With
           .Start()
           .WaitForExit()

           Dim _StandardOutput As String = .StandardOutput.ReadToEnd
           If _StandardOutput.Contains("There are open files and/or
incomplete directory searches pending on the connection") Then
               .StandardInput.WriteLine("y")
               .StandardInput.Flush()
           Else
               If Not _StandardOutput.StartsWith(String.Format("{0}: was
deleted successfully.", DriveLetter)) Then Throw New Exception("The network
drive was not unmapped.")
           End If
       End With
   End Sub

However, I find this does not work. Further research reveals that if
net.exe shows "There are open files and/or incomplete directory searches
pending on the connection" for user to input "y", the net.exe process will
not terminate at all, it will wait for the user input through standard
input. However, I find that if we set RedirectStandardOutput or
RedirectStandardInput to true and start the net.exe process, the net.exe
will generate the output and terminate itself immediately without waiting
for the standard input. So net.exe does not give us the chance to input
"y".

I suspect net.exe behaves this way for security reason, because it does not
allow some hacker process to lauch it in background with
RedirectStandardOutput/RedirectStandardInput for driver mapping. Anyway,
this approach can not be done because of this limitation.

So I recommand you go with "Ben Voigt"'s suggestion of p/invoking win32 API
to close the connection. More specificly, you may use WNetCancelConnection2
to close the connection and the second parameter tells the system to close
the connection even there are open files or jobs on the connection. The
sample code snippet below works well on my side, for your information:

Dim CONNECT_UPDATE_PROFILE As Integer = 1
   Dim NO_ERROR As Integer = 0
   <DllImport("mpr.dll", CharSet:=CharSet.Auto)> _
   Public Shared Function WNetCancelConnection2(ByVal name As String,
ByVal flags As Integer, ByVal force As Boolean) As Integer
   End Function

   Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button2.Click
       Dim ret As Integer = WNetCancelConnection2("z:",
CONNECT_UPDATE_PROFILE, True)
       If Not ret = NO_ERROR Then
           MessageBox.Show(Marshal.GetLastWin32Error())
       End If
   End Sub

Hope this helps.

Best regards,
Jeffrey Tan
Microsoft Online Community Support
==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscriptions/managednewsgroups/default.aspx#notif
ications.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscriptions/support/default.aspx.
==================================================
This posting is provided "AS IS" with no warranties, and confers no rights.

Rate this thread:







Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.