开发者

vb.net application works with files dragged onto the exe, but crashes if there's a space in the file's path

I'm developing an application in vb.net. You drag any type of file onto the exe, and a window pops up with some options for the file, then it saves the file to a different location, works some SQL magic, etc. It works great for the most part.

The only issue I've found is that if the path of the file contains any spaces, the application will crash immediately with the error window: http://i.stack.imgur.com/mVamO.png

I'm using: Private filename as String = Command$ This is located right inside my form's class declaration, not within a sub/function. Without this line, my program runs fine (although useless, without accessing the file). I've also tried (I think this was it, I don't have the code with me at the moment): Private filename as String = Environment.CommandLine And it had the same issue.

So, in vb.net, is there a way to drag a file onto an exe and use that pat开发者_Python百科h name, even if there are spaces in the path name?


Windows will put double-quotes around the passed command line argument if the path to the dragged file contains spaces. Trouble is, you are using an ancient VB6 way to retrieve the argument, you see the double quotes. Which .NET then objects against, a double quote is not valid in a path name. Use this:

        Dim path = Command$.Replace("""", "")

Or the .NET way:

Sub Main(ByVal args() As String)
    If args.Length > 0 then
        Dim path = args(0)
        MsgBox(path)
        '' do something with it..
    End If
End Sub


If possible, do post your code as it's pretty much anything that can go wrong. Normally, after receiving CommandLine Arg, I would try to use a System.IO.File wrapper and use built-in mechanisms to verify file and then proceed with it further using IO as much as possible. If you are attempting to directly manipulate the file, then the spaces might become an issue.

In addition, there is a way to convert long file path + name to old DOS’s 8.3 magical file path + name. However, I’ll go into R&D after I see what you are doing in code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜