Process.ErrorDataReceived イベントとは? わかりやすく解説

Weblio 辞書 > コンピュータ > .NET Framework クラス ライブラリ リファレンス > Process.ErrorDataReceived イベントの意味・解説 

Process.ErrorDataReceived イベント

メモ : このイベントは、.NET Framework version 2.0新しく追加されたものです。

アプリケーションリダイレクトされた StandardError ストリーム書き込む場合発生します

名前空間: System.Diagnostics
アセンブリ: System (system.dll 内)
構文構文

Public Event ErrorDataReceived As
 DataReceivedEventHandler
Dim instance As Process
Dim handler As DataReceivedEventHandler

AddHandler instance.ErrorDataReceived, handler
public event DataReceivedEventHandler ErrorDataReceived
public:
event DataReceivedEventHandler^ ErrorDataReceived {
    void add (DataReceivedEventHandler^ value);
    void remove (DataReceivedEventHandler^ value);
}
/** @event */
public void add_ErrorDataReceived (DataReceivedEventHandler
 value)

/** @event */
public void remove_ErrorDataReceived (DataReceivedEventHandler
 value)
JScript では、イベント使用できますが、新規に宣言することはできません。
解説解説
使用例使用例

net view コマンド使用してリモート コンピュータ利用可能ネットワーク リソース一覧表示する例を次に示しますユーザー対象コンピュータ名をコマンド ライン引数として指定しますまた、エラー出力ファイル名指定できます。この例では、net コマンド出力収集しプロセス完了待機して出力結果コンソール書き込みますユーザーオプションエラー ファイル指定した場合は、そのファイルエラー書き込まれます。

' Define the namespaces used by this sample.
Imports System
Imports System.Text
Imports System.Globalization
Imports System.IO
Imports System.Diagnostics
Imports System.Threading
Imports System.ComponentModel
Imports Microsoft.VisualBasic


Namespace ProcessAsyncStreamSamples
   
   Class ProcessAsyncErrorRedirection
      ' Define static variables shared by class methods.
      Private Shared streamError As
 StreamWriter = Nothing
      Private Shared netErrorFile As
 String = ""
      Private Shared netOutput As
 StringBuilder = Nothing
      Private Shared errorRedirect As
 Boolean = False
      Private Shared errorsWritten As
 Boolean = False
      
      Public Shared Sub
 RedirectNetCommandStreams()
         Dim netArguments As String
         Dim netProcess As Process
         
         ' Get the input computer name.
         Console.WriteLine("Enter the computer name for the net
 view command:")
         netArguments = Console.ReadLine().ToUpper(CultureInfo.InvariantCulture)
         If String.IsNullOrEmpty(netArguments)
 Then
            ' Default to the help command if there is 
            ' not an input argument.
            netArguments = "/?"
         End If
         
         ' Check if errors should be redirected to a file.
         errorsWritten = False
         Console.WriteLine("Enter a fully qualified path to an
 error log file")
         Console.WriteLine("  or just press Enter to write errors
 to console:")
         netErrorFile = Console.ReadLine().ToUpper(CultureInfo.InvariantCulture)
         If Not String.IsNullOrEmpty(netErrorFile)
 Then
            errorRedirect = True
         End If
         
         ' Note that at this point, netArguments and netErrorFile
         ' are set with user input.  If the user did not specify
         ' an error file, then errorRedirect is set to false.

         ' Initialize the process and its StartInfo properties.
         netProcess = New Process()
         netProcess.StartInfo.FileName = "Net.exe"
         
         ' Build the net command argument list.
         netProcess.StartInfo.Arguments = String.Format("view
 {0}", _
                                                        netArguments)
         
         ' Set UseShellExecute to false for redirection.
         netProcess.StartInfo.UseShellExecute = False
         
         ' Redirect the standard output of the net command.  
         ' Read the stream asynchronously using an event handler.
         netProcess.StartInfo.RedirectStandardOutput = True
         AddHandler netProcess.OutputDataReceived, _
                            AddressOf NetOutputDataHandler
         netOutput = new StringBuilder()
         
         If errorRedirect Then
            ' Redirect the error output of the net command. 
            netProcess.StartInfo.RedirectStandardError = True
            AddHandler netProcess.ErrorDataReceived, _
                            AddressOf NetErrorDataHandler
         Else
            ' Do not redirect the error output.
            netProcess.StartInfo.RedirectStandardError = False
         End If
         
         Console.WriteLine(ControlChars.Lf + "Starting process:
 NET {0}", _
                           netProcess.StartInfo.Arguments)
         If errorRedirect Then
            Console.WriteLine("Errors will be written to the file
 {0}", _
                           netErrorFile)
         End If
         
         ' Start the process.
         netProcess.Start()
         
         ' Start the asynchronous read of the standard output stream.
         netProcess.BeginOutputReadLine()
         
         If errorRedirect Then
            ' Start the asynchronous read of the standard
            ' error stream.
            netProcess.BeginErrorReadLine()
         End If
         
         ' Let the net command run, collecting the output.
         netProcess.WaitForExit()
      
         If Not streamError Is
 Nothing Then
             ' Close the error file.
             streamError.Close()
         Else 
             ' Set errorsWritten to false if the stream is not
             ' open.   Either there are no errors, or the error
             ' file could not be opened.
             errorsWritten = False
         End If
   
         If netOutput.Length > 0 Then
            ' If the process wrote more than just
            ' white space, write the output to the console.
            Console.WriteLine()
            Console.WriteLine("Public network shares from net
 view:")
            Console.WriteLine()
            Console.WriteLine(netOutput)
            Console.WriteLine()
         End If
         
         If errorsWritten Then
            ' Signal that the error file had something 
            ' written to it.
            Dim errorOutput As String()
            errorOutput = File.ReadAllLines(netErrorFile)
            If errorOutput.Length > 0 Then

                Console.WriteLine(ControlChars.Lf + _
                    "The following error output was appended to
 {0}.", _
                    netErrorFile)
                Dim errLine as String
                For Each errLine in
 errorOutput
                    Console.WriteLine("  {0}", errLine)
                Next
          
                Console.WriteLine()
            End If
         End If
         
         netProcess.Close()
      End Sub 
      
      
      Private Shared Sub
 NetOutputDataHandler(sendingProcess As Object,
 _
          outLine As DataReceivedEventArgs)

         ' Collect the net view command output.
         If Not String.IsNullOrEmpty(outLine.Data)
 Then
            ' Add the text to the collected output.
            netOutput.Append(Environment.NewLine + "  "
 + outLine.Data)
         End If
      End Sub 
       
      
      Private Shared Sub
 NetErrorDataHandler(sendingProcess As Object,
 _
          errLine As DataReceivedEventArgs)

         ' Write the error text to the file if there is something to
         ' write and an error file has been specified.

         If Not String.IsNullOrEmpty(errLine.Data)
 Then

            If Not errorsWritten Then
                If streamError Is Nothing
 Then
                    ' Open the file.
                    Try 
                        streamError = New StreamWriter(netErrorFile,
 true)
                    Catch e As Exception
                        Console.WriteLine("Could not open error
 file!")
                        Console.WriteLine(e.Message.ToString())
                    End Try
                End If

                If Not streamError Is
 Nothing Then

                    ' Write a header to the file if this is the first
                    ' call to the error output handler.
                    streamError.WriteLine()
                    streamError.WriteLine(DateTime.Now.ToString())
                    streamError.WriteLine("Net View error output:")

                End If

                errorsWritten = True
            End If
                     
            If Not streamError Is
 Nothing Then
                  
                ' Write redirected errors to the file.
                streamError.WriteLine(errLine.Data)
                streamError.Flush()
             End If
          End If
      End Sub 
   End Class  
End Namespace 
// Define the namespaces used by this sample.
using System;
using System.Text;
using System.Globalization;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.ComponentModel;


namespace ProcessAsyncStreamSamples
{

    class ProcessNetStreamRedirection
    {
        // Define static variables shared by class methods.
        private static StreamWriter streamError
 =null;
        private static String netErrorFile
 = "";
        private static StringBuilder netOutput
 = null;
        private static bool
 errorRedirect = false;
        private static bool
 errorsWritten = false;

        public static void
 RedirectNetCommandStreams()
        {
            String netArguments;
            Process netProcess;

            // Get the input computer name.
            Console.WriteLine("Enter the computer name for
 the net view command:");
            netArguments = Console.ReadLine().ToUpper(CultureInfo.InvariantCulture);
            if (String.IsNullOrEmpty(netArguments))
            {
                // Default to the help command if there is not an input
 argument.
                netArguments = "/?";
            }
               
            // Check if errors should be redirected to a file.
            errorsWritten = false;
            Console.WriteLine("Enter a fully qualified path to an error log
 file");
            Console.WriteLine("  or just press Enter to write errors to console:");
            netErrorFile = Console.ReadLine().ToUpper(CultureInfo.InvariantCulture);
            if (!String.IsNullOrEmpty(netErrorFile))
            {
                errorRedirect = true;
            }

            // Note that at this point, netArguments and netErrorFile
            // are set with user input.  If the user did not specify
            // an error file, then errorRedirect is set to false.
      
            // Initialize the process and its StartInfo properties.
            netProcess = new Process();
            netProcess.StartInfo.FileName = "Net.exe";
            
            // Build the net command argument list.
            netProcess.StartInfo.Arguments = String.Format("view {0}",
 
                netArguments);

            // Set UseShellExecute to false for redirection.
            netProcess.StartInfo.UseShellExecute = false;

            // Redirect the standard output of the net command.  
            // This stream is read asynchronously using an event handler.
            netProcess.StartInfo.RedirectStandardOutput = true;
            netProcess.OutputDataReceived += new DataReceivedEventHandler(NetOutputDataHandler);
            netOutput = new StringBuilder();
   
            if (errorRedirect)
            {
                // Redirect the error output of the net command. 
                netProcess.StartInfo.RedirectStandardError = true;
                netProcess.ErrorDataReceived += new DataReceivedEventHandler(NetErrorDataHandler);
            }
            else 
            {
                // Do not redirect the error output.
                netProcess.StartInfo.RedirectStandardError = false;
            }

            Console.WriteLine("\nStarting process: net {0}", 
                netProcess.StartInfo.Arguments);
            if (errorRedirect)
            {
                Console.WriteLine("Errors will be written to the file {0}",
 
                    netErrorFile);
            }

            // Start the process.
            netProcess.Start();

            // Start the asynchronous read of the standard output stream.
            netProcess.BeginOutputReadLine();

            if (errorRedirect)
            {
                // Start the asynchronous read of the standard
                // error stream.
                netProcess.BeginErrorReadLine();
            }

            // Let the net command run, collecting the output.
            netProcess.WaitForExit();

            if (streamError != null)
            {
                // Close the error file.
                streamError.Close();
            }
            else 
            {
                // Set errorsWritten to false if the stream is not
                // open.   Either there are no errors, or the error
                // file could not be opened.
                errorsWritten = false;
            }

            if (netOutput.Length > 0)
            {
                // If the process wrote more than just
                // white space, write the output to the console.
                Console.WriteLine("\nPublic network shares from net view:\n{0}\n",
 
                    netOutput);
            }

            if (errorsWritten)
            {
                // Signal that the error file had something 
                // written to it.
                String [] errorOutput = File.ReadAllLines(netErrorFile);
                if (errorOutput.Length > 0)
                {
                    Console.WriteLine("\nThe following error output was appended
 to {0}.",
                        netErrorFile);
                    foreach (String errLine in
 errorOutput)
                    {
                        Console.WriteLine("  {0}", errLine);
                    }
                }
                Console.WriteLine();
            }

            netProcess.Close();

        }

        private static void
 NetOutputDataHandler(object sendingProcess, 
            DataReceivedEventArgs outLine)
        {
            // Collect the net view command output.
            if (!String.IsNullOrEmpty(outLine.Data))
            {
                // Add the text to the collected output.
                netOutput.Append(Environment.NewLine + "  " + outLine.Data);
            }
        }

        private static void
 NetErrorDataHandler(object sendingProcess, 
            DataReceivedEventArgs errLine)
        {
            // Write the error text to the file if there is something
            // to write and an error file has been specified.

            if (!String.IsNullOrEmpty(errLine.Data))
            {
                if (!errorsWritten)
                {
                    if (streamError == null)
                    {
                        // Open the file.
                        try 
                        {
                            streamError = new StreamWriter(netErrorFile,
 true);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Could not open error file!");
                            Console.WriteLine(e.Message.ToString());
                        }
                    }

                    if (streamError != null)
                    {
                        // Write a header to the file if this is the
 first
                        // call to the error output handler.
                        streamError.WriteLine();
                        streamError.WriteLine(DateTime.Now.ToString());
                        streamError.WriteLine("Net View error output:");
                    }
                    errorsWritten = true;
                }

                if (streamError != null)
                {
                    // Write redirected errors to the file.
                    streamError.WriteLine(errLine.Data);
                    streamError.Flush();
                }
            }
        }
    }
} 
// Define the namespaces used by this sample.
#using <System.dll>

using namespace System;
using namespace System::Text;
using namespace System::Globalization;
using namespace System::IO;
using namespace System::Diagnostics;
using namespace System::Threading;
using namespace System::ComponentModel;

ref class ProcessNetStreamRedirection
{
private:
   // Define static variables shared by class methods.
   static StreamWriter^ streamError = nullptr;
   static String^ netErrorFile = "";
   static StringBuilder^ netOutput = nullptr;
   static bool errorRedirect = false;
   static bool errorsWritten = false;

public:
   static void RedirectNetCommandStreams()
   {
      String^ netArguments;
      Process^ netProcess;
      
      // Get the input computer name.
      Console::WriteLine( "Enter the computer name for the
 net view command:" );
      netArguments = Console::ReadLine()->ToUpper( CultureInfo::InvariantCulture
 );
      if ( String::IsNullOrEmpty( netArguments ) )
      {
         // Default to the help command if there is not an input argument.
         netArguments = "/?";
      }
      
      // Check if errors should be redirected to a file.
      errorsWritten = false;
      Console::WriteLine( "Enter a fully qualified path to an error log file"
 );
      Console::WriteLine( "  or just press Enter to write errors to console:"
 );
      netErrorFile = Console::ReadLine()->ToUpper( CultureInfo::InvariantCulture
 );
      if (  !String::IsNullOrEmpty( netErrorFile ) )
      {
         errorRedirect = true;
      }
      
      // Note that at this point, netArguments and netErrorFile
      // are set with user input.  If the user did not specify
      // an error file, then errorRedirect is set to false.

      // Initialize the process and its StartInfo properties.
      netProcess = gcnew Process;
      netProcess->StartInfo->FileName = "Net.exe";
      
      // Build the net command argument list.
      netProcess->StartInfo->Arguments = String::Format( "view {0}",
 netArguments );
      
      // Set UseShellExecute to false for redirection.
      netProcess->StartInfo->UseShellExecute = false;
      
      // Redirect the standard output of the net command.  
      // This stream is read asynchronously using an event handler.
      netProcess->StartInfo->RedirectStandardOutput = true;
      netProcess->OutputDataReceived += gcnew DataReceivedEventHandler( NetOutputDataHandler
 );
      netOutput = gcnew StringBuilder;
      if ( errorRedirect )
      {
         
         // Redirect the error output of the net command. 
         netProcess->StartInfo->RedirectStandardError = true;
         netProcess->ErrorDataReceived += gcnew DataReceivedEventHandler( NetErrorDataHandler
 );
      }
      else
      {
         
         // Do not redirect the error output.
         netProcess->StartInfo->RedirectStandardError = false;
      }

      Console::WriteLine( "\nStarting process: net {0}",
         netProcess->StartInfo->Arguments );
      if ( errorRedirect )
      {
         Console::WriteLine( "Errors will be written to the file {0}",
 netErrorFile );
      }
      
      // Start the process.
      netProcess->Start();
      
      // Start the asynchronous read of the standard output stream.
      netProcess->BeginOutputReadLine();

      if ( errorRedirect )
      {
         // Start the asynchronous read of the standard
         // error stream.
         netProcess->BeginErrorReadLine();
      }
      
      // Let the net command run, collecting the output.
      netProcess->WaitForExit();

      if ( streamError != nullptr )
      {
         // Close the error file.
         streamError->Close();
      }
      else
      {
         // Set errorsWritten to false if the stream is not
         // open.   Either there are no errors, or the error
         // file could not be opened.
         errorsWritten = false;
      }

      if ( netOutput->Length > 0 )
      {
         // If the process wrote more than just
         // white space, write the output to the console.
         Console::WriteLine( "\nPublic network shares from net view:\n{0}\n"
,
            netOutput->ToString() );
      }

      if ( errorsWritten )
      {
         // Signal that the error file had something 
         // written to it.
         array<String^>^errorOutput = File::ReadAllLines( netErrorFile );
         if ( errorOutput->Length > 0 )
         {
            Console::WriteLine( "\nThe following error output was appended to
 {0}.",
               netErrorFile );
            System::Collections::IEnumerator^ myEnum = errorOutput->GetEnumerator();
            while ( myEnum->MoveNext() )
            {
               String^ errLine = safe_cast<String^>(myEnum->Current);
               Console::WriteLine( "  {0}", errLine );
            }
         }
         Console::WriteLine();
      }

      netProcess->Close();

   }

private:
   static void NetOutputDataHandler( Object^
 /*sendingProcess*/,
      DataReceivedEventArgs^ outLine )
   {
      // Collect the net view command output.
      if (  !String::IsNullOrEmpty( outLine->Data ) )
      {
         // Add the text to the collected output.
         netOutput->AppendFormat(  "\n  {0}", outLine->Data );
      }
   }

   static void NetErrorDataHandler( Object^
 /*sendingProcess*/,
      DataReceivedEventArgs^ errLine )
   {
      // Write the error text to the file if there is something to 
      // write and an error file has been specified.

      if (  !String::IsNullOrEmpty( errLine->Data ) )
      {
         if (  !errorsWritten )
         {
            if ( streamError == nullptr )
            {
               // Open the file.
               try
               {
                  streamError = gcnew StreamWriter( netErrorFile,true
 );
               }
               catch ( Exception^ e ) 
               {
                  Console::WriteLine(  "Could not open error file!" );
                  Console::WriteLine( e->Message->ToString() );
               }
            }

            if ( streamError != nullptr )
            {
               // Write a header to the file if this is the first
               // call to the error output handler.
               streamError->WriteLine();
               streamError->WriteLine( DateTime::Now.ToString() );
               streamError->WriteLine(  "Net View error output:" );
            }
            errorsWritten = true;
         }

         if ( streamError != nullptr )
         {
            // Write redirected errors to the file.
            streamError->WriteLine( errLine->Data );
            streamError->Flush();
         }
      }
   }
};
.NET Framework のセキュリティ.NET Frameworkセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
Process クラス
Process メンバ
System.Diagnostics 名前空間
ProcessStartInfo.RedirectStandardError
Process.StandardError プロパティ
BeginErrorReadLine
CancelErrorRead
DataReceivedEventHandler デリゲート


このページでは「.NET Framework クラス ライブラリ リファレンス」からProcess.ErrorDataReceived イベントを検索した結果を表示しています。
Weblioに収録されているすべての辞書からProcess.ErrorDataReceived イベントを検索する場合は、下記のリンクをクリックしてください。
 全ての辞書からProcess.ErrorDataReceived イベント を検索

英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「Process.ErrorDataReceived イベント」の関連用語

Process.ErrorDataReceived イベントのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



Process.ErrorDataReceived イベントのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2025 Microsoft.All rights reserved.

©2025 GRAS Group, Inc.RSS