开发者

How to specify a path with spaces for StreamWriter

In VB.Net, how do I provide the StreamWriter constructor with a path that includes spaces? StreamWriter("""C:\Users\Public\Public User开发者_如何学Gos\file.txt""") does not work.


Here is a working code example:

Dim fs As New System.IO.StreamWriter("e:\test 123.txt")
fs.Write("hello")
fs.Close()

UPDATE:

The new example for folder with space(s):

'this is your filename
Dim Filename As String = "e:\folder with space\test 123.txt"

'this is your folder
Dim Folderpath As String = System.IO.Path.GetDirectoryName(Filename)

'now do checking if the folder exists, if not create the folder
If System.IO.Directory.Exists(Folderpath) = False Then
    System.IO.Directory.CreateDirectory(Folderpath)
End If

'now create the file as usual
Dim fs As New System.IO.StreamWriter("e:\folder with space\test 123.txt")
fs.Write("hello")
fs.Close()

The reason for your code didn't compile because you have not create the folder before creating the file, ie that folder must be existed before you can create your file.


You don't put quotes around the string you pass to the StreamReader constructor. Quotes are only used when you use, say, the command line. Or anything else that uses spaces as separators between arguments. The program requires those double quotes to recognize an argument with an embedded space.

Not necessary here, there's no ambiguity since the argument only takes the path to a single file. The only exception to that rule that I know of is the ProcessStartInfo.Arguments property.

So, just put single double quotes around the string, the syntax that the compiler requires. Your real problem is the name of the folder. Windows Explorer shows a different name for the folders in c:\users\public. For example c:\users\public\videos is displayed in the Explorer window as "Public Videos". It's trying to be helpful by expanding the abbreviated name. Your program however has to use the real folder name. Which is probably "users", not "Public Users". To find out for sure, use the command line (cmd.exe). Use cd \users\public and dir /a.

Last but not least, that folder has a different name on different versions of Windows. You should use Environment.GetFolderPath(). "Public Users" isn't a standard folder name however, not sure why you are using it.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜