VB.NET 获取在我的程序中打开的文件的目录 [英] VB.NET get directory of a file opened in my program
问题描述
我有这段代码可以让所有带有.whatever"扩展名的文件用我的程序打开:
I have this code that makes it so that all files with the ".whatever" extension open with my program:
If Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(".whatever\shell\open\command", True) Is Nothing Then
Dim icotouse As String = Path.GetTempPath() & "\whatever.ico"
My.Computer.Registry.ClassesRoot.CreateSubKey(".whatever").SetValue("", "whatever", Microsoft.Win32.RegistryValueKind.String)
My.Computer.Registry.ClassesRoot.CreateSubKey("whatever\shell\open\command").SetValue("", Application.ExecutablePath, Microsoft.Win32.RegistryValueKind.String)
My.Computer.Registry.ClassesRoot.CreateSubKey("whatever\DefaultIcon").SetValue("", icotouse)
End If
现在当用户双击.whatever"文件时,它将在我的程序中打开.
Now when the user double clicks the ".whatever" file, it will open in my program.
当我在我的程序中打开.whatever"文件时,如何获取它所在的目录?例如,用户单击桌面上的一个文件 [C:\Users\Example\Desktop\file.whatever],当他们单击它时,它会在我的程序中打开,我可以为该目录分配一个变量名?>
How do I get the directory of where the ".whatever" file was when I open it in my program? For example, user clicks a file on their desktop [C:\Users\Example\Desktop\file.whatever] and when they click it, it opens up in my program, and I can assign a variable name to that directory?
推荐答案
首先,您需要让 Windows 将文件路径传递给您的程序.这是通过将 %1
添加到 command
键的默认值来实现的.
First of all you need to make Windows pass the path of the file to your program. This is done by adding %1
to the command
key's default value.
将创建 command
键的代码更改为:
Change your code that creates the command
key to this:
My.Computer.Registry.ClassesRoot.CreateSubKey("whatever\shell\open\command").SetValue("", Application.ExecutablePath & " %1", Microsoft.Win32.RegistryValueKind.String)
其次,要获取发送到程序的文件的路径,您可以使用例如 Environment.GetCommandLineArgs()
.
Secondly, to get the path of the file sent to your program, you'd use for example Environment.GetCommandLineArgs()
.
把它放在类似 Form_Load
事件的地方:
Put this somewhere like in the Form_Load
event:
Dim Arguments() As String = Environment.GetCommandLineArgs()
If Arguments.Length > 1 Then 'If there's more than one argument, it means that something (like a file) was passed to your application.
End If
现在,If
语句检查参数是否已发送到您的应用程序.要获取文件的路径,您只需将这样的内容放入其中:
Now, the If
-statement checks if a parameter was sent to your application. To get the path of your file you'd simply put something like this inside it:
Dim FilePath As String = Arguments(1)
'Will give you for example: C:\Users\Example\Desktop\file.whatever
但是如果你想获取文件的目录,你可以执行以下操作:
But if you want to get the file's directory, you can do the following below:
Dim FileDirectory As String = IO.Path.GetDirectoryName(FilePath)
'Will give you for example: C:\Users\Example\Desktop
这篇关于VB.NET 获取在我的程序中打开的文件的目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!