【解決方法】C# で USB から自動実行する方法

プログラミングQA


How make autorun from usb in c# 

私が試したこと:

How make autorun from usb in c# 

解決策 1

あなたがやろうとしていることはユニークではありません。

開始するのに最適な場所は次のとおりです。 C# で USB から自動実行する方法 – Google 検索[^]

チャットGPT[^] あなたがそれを尋ねるとき、興味深い応答もあります: c# で USB から自動実行する方法.

与えられた応答は次のとおりです。

引用:

C# を使用して USB ドライブから自動実行を作成するには、System.Management 名前空間を使用して、USB ドライブがコンピューターに接続されていることを検出し、USB ドライブから実行可能ファイルを実行します。 これを行う方法を示すサンプル コードを次に示します。

C# コード例は次のとおりです。

C#
using System;
using System.Management;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // Define the query to detect USB drive insertion
        WqlEventQuery query = new WqlEventQuery("SELECT * FROM Win32_VolumeChangeEvent WHERE EventType = 2");

        // Initialize the watcher for USB drive insertion
        ManagementEventWatcher watcher = new ManagementEventWatcher();
        watcher.Query = query;
        watcher.EventArrived += new EventArrivedEventHandler(USBInserted);

        // Start watching for USB drive insertion
        watcher.Start();

        // Wait for USB drive insertion events
        while (true) { }
    }

    static void USBInserted(object sender, EventArrivedEventArgs e)
    {
        // Get the drive letter of the inserted USB drive
        string driveName = e.NewEvent.Properties["DriveName"].Value.ToString();
        string driveLetter = driveName.Substring(0, 2);

        // Check if the USB drive contains an autorun.inf file
        string autorunFile = driveLetter + "autorun.inf";
        if (File.Exists(autorunFile))
        {
            // Get the path to the executable to be run
            string executablePath = driveLetter + "myprogram.exe";

            // Check if the executable file exists
            if (File.Exists(executablePath))
            {
                // Run the executable file
                System.Diagnostics.Process.Start(executablePath);
            }
        }
    }
}

そして要約:

引用:

このコードでは、USB ドライブがコンピューターに挿入されるたびに、USBInserted メソッドが呼び出されます。 このメソッドは、USB ドライブに autorun.inf ファイルが含まれているかどうかを確認し、含まれている場合は、USB ドライブから myprogram.exe 実行可能ファイルを実行します。 myprogram.exe を独自の実行可能ファイルの名前に置き換える必要があることに注意してください。

あなたが何をしたいのか正確にはわかりませんが、調査に使用できるツールがあります。

コメント

タイトルとURLをコピーしました