From 6c5011ad68ee0ee3723003c67a3a518fbf0abac9 Mon Sep 17 00:00:00 2001
From: 2dust <31833384+2dust@users.noreply.github.com>
Date: Thu, 30 Jan 2025 10:46:04 +0800
Subject: [PATCH] Try to remove the tun device when restarting the service in
 Windows

https://github.com/2dust/v2rayN/pull/6561
---
 v2rayN/ServiceLib/Common/WindowsUtils.cs | 28 +++++++++++++++++--
 v2rayN/ServiceLib/Handler/CoreHandler.cs | 13 +++++++--
 v2rayN/v2rayN/Common/WindowsUtils.cs     | 35 ++----------------------
 3 files changed, 38 insertions(+), 38 deletions(-)

diff --git a/v2rayN/ServiceLib/Common/WindowsUtils.cs b/v2rayN/ServiceLib/Common/WindowsUtils.cs
index 83e2ee57800..80d2035733d 100644
--- a/v2rayN/ServiceLib/Common/WindowsUtils.cs
+++ b/v2rayN/ServiceLib/Common/WindowsUtils.cs
@@ -1,4 +1,7 @@
-using Microsoft.Win32;
+using System.Diagnostics;
+using System.Security.Cryptography;
+using System.Text;
+using Microsoft.Win32;
 
 namespace ServiceLib.Common
 {
@@ -50,5 +53,24 @@ public static void RegWriteValue(string path, string name, object value)
                 regKey?.Close();
             }
         }
-    }
-}
\ No newline at end of file
+
+        public static async Task RemoveTunDevice()
+        {
+	        try
+	        {
+		        var sum = MD5.HashData(Encoding.UTF8.GetBytes("wintunsingbox_tun"));
+		        var guid = new Guid(sum);
+		        var pnpUtilPath = @"C:\Windows\System32\pnputil.exe";
+		        var arg = $$""" /remove-device  "SWD\Wintun\{{{guid}}}" """;
+
+				// Try to remove the device
+				await Utils.GetCliWrapOutput(pnpUtilPath, arg);
+				 
+			}
+			catch (Exception ex)
+			{
+				Logging.SaveLog(_tag, ex);
+			}
+		}
+	}
+}
diff --git a/v2rayN/ServiceLib/Handler/CoreHandler.cs b/v2rayN/ServiceLib/Handler/CoreHandler.cs
index 44215204043..399b4a9fbdd 100644
--- a/v2rayN/ServiceLib/Handler/CoreHandler.cs
+++ b/v2rayN/ServiceLib/Handler/CoreHandler.cs
@@ -1,4 +1,4 @@
-using System.Diagnostics;
+using System.Diagnostics;
 using System.Text;
 
 namespace ServiceLib.Handler
@@ -83,7 +83,14 @@ public async Task LoadCore(ProfileItem? node)
             UpdateFunc(false, string.Format(ResUI.StartService, DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")));
             await CoreStop();
             await Task.Delay(100);
-            await CoreStart(node);
+
+			if (Utils.IsWindows() && _config.TunModeItem.EnableTun)
+			{
+				await Task.Delay(100);
+				await WindowsUtils.RemoveTunDevice();
+			}
+
+			await CoreStart(node);
             await CoreStartPreService(node);
             if (_process != null)
             {
@@ -368,4 +375,4 @@ private async Task<string> CreateLinuxShellFile(string cmdLine, string fileName)
 
         #endregion Linux
     }
-}
\ No newline at end of file
+}
diff --git a/v2rayN/v2rayN/Common/WindowsUtils.cs b/v2rayN/v2rayN/Common/WindowsUtils.cs
index 6a0792d8c89..3e1399879f0 100644
--- a/v2rayN/v2rayN/Common/WindowsUtils.cs
+++ b/v2rayN/v2rayN/Common/WindowsUtils.cs
@@ -1,4 +1,4 @@
-using Microsoft.Win32;
+using Microsoft.Win32;
 using System.Diagnostics;
 using System.Drawing;
 using System.Runtime.InteropServices;
@@ -64,36 +64,7 @@ public static ImageSource IconToImageSource(Icon icon)
                 BitmapSizeOptions.FromEmptyOptions());
         }
 
-        public static void RemoveTunDevice()
-        {
-            try
-            {
-                var sum = MD5.HashData(Encoding.UTF8.GetBytes("wintunsingbox_tun"));
-                var guid = new Guid(sum);
-                string pnputilPath = @"C:\Windows\System32\pnputil.exe";
-                string arg = $$""" /remove-device  "SWD\Wintun\{{{guid}}}" """;
-
-                // Try to remove the device
-                Process proc = new()
-                {
-                    StartInfo = new()
-                    {
-                        FileName = pnputilPath,
-                        Arguments = arg,
-                        RedirectStandardOutput = true,
-                        UseShellExecute = false,
-                        CreateNoWindow = true
-                    }
-                };
-
-                proc.Start();
-                var output = proc.StandardOutput.ReadToEnd();
-                proc.WaitForExit();
-            }
-            catch
-            {
-            }
-        }
+       
 
         public static void SetDarkBorder(Window window, string? theme)
         {
@@ -136,4 +107,4 @@ public enum DWMWINDOWATTRIBUTE : uint
 
         #endregion Windows API
     }
-}
\ No newline at end of file
+}