In VB.Net, how do I provide the StreamWriter constructor with a path that includes spaces? StreamWriter("""C:\Users\Public\Public Users\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.
Related
I am working in Visual Basic 2017. I have tried to add the file to the Debug folder, but then it just shows that the txt file ienter image description heres missing. I don't have the option under the "Word Solution".. How can I make the file show up? It keeps telling me it doesn't exist.
Dim inFile As IO.StreamReader
Const FileName As String = "words.txt"
Dim subscript As Integer
You can get the path of the directory (Debug or Release or any other) of the *.exe file with:
Dim directory as String = My.Application.Info.DirectoryPath
Using this information, you can then construct the full path with
Dim path As String = IO.Path.Combine(directory, FileName)
If IO.File.Exists(path) Then
...
You can check in Windows File Explorer to see where the file actually is (notice the Copy Path on the ribbon). In File Explorer you will see that the .exe you are running is down 2 directories from the Words Project directory. The double dots in the path is an old DOS way to navigating around directories without having to type out the whole path. This tells the compiler to find the file up 2 directories from the current directory.
For testing purposes this will work. For a release version you could add the file to Resources and access it the same way in any version.
You don't need a stream for a text file. .ReadAllLines returns an array of the lines in the text file
Private Sub OpCode()
Dim words = File.ReadAllLines("..\..\words.txt")
End Sub
Hi i've used the code bellow successfully at the beginning but i don't know what i did so it stopped creating the file MessageIO.dat under the folder (ProgramFiles)\UniWin Activator Data
i used this code: (result: created only folder UniWin Activator Data)
Dim UniWinPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "UniWin Activator Data")
Directory.CreateDirectory(UniWinPath)
Dim MsgIO = Path.Combine(UniWinPath, "\MessageIO.dat")
File.Create(MsgIO)
and used this: (result: error at the command File.Create)
Dim UniWinPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "UniWin Activator Data\MessageIO.dat")
File.Create(UniWinPath)
and used this: (result: nothing happened)
Dim UniWinPath As String = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "UniWin Activator Data")
Dim MsgIO = Path.Combine(UniWinPath, "\MessageIO.dat")
File.Create(MsgIO)
what's the way to create that file? (I have admin rights already)
The first of your code is perfectly fine. Just change Dim MsgIO = Path.Combine(UniWinPath, "\MessageIO.dat") to Dim MsgIO = Path.Combine(UniWinPath, "MessageIO.dat"). (Remove the backslash). Path.Combine automatically adds one. And as always, to access special directories, make sure you have Administrator Privilleges. The reason the last two codes aren't working is that File.Create creates a file in an existing directory. It can't create the directory itself.
When combining paths, you should not specify the "\" char at begining of the second path item as this will mean the root path!
for example, Path.Combine("D:\Folder1", "\MessageIO.dat") will result "\MessageIO.dat". but you have to write Path.Combine("D:\Folder1", "MessageIO.dat") which will return "D:\Folder1\MessageIO.dat"
Note: in windows 7 or above, access to special folders like as Program Files require special permissions! check that your app has such permission. (you can test for other norman folder first to ensure other parts of your code is ok)
I'm making a console application and I want to see what files is in a folder
For Each foundFile As String In My.Computer.FileSystem.GetFiles("c:\users\zac\desktop\booked vehicle\requested\")
Console.WriteLine(foundFile)
Next
after using this code and find that the folder is empty I need an If statement that say's
If foundfile has no files then
tell user no files found
end if
but I don't know how to write this so Visual Basic understands.
Load the files into a variable then check the count.
Dim files = My.Computer.FileSystem.GetFiles("c:\users\zac\desktop\booked vehicle\requested\")
If files.Count = 0 Then
'tell user no files
Else
For Each file In files
Console.WriteLine(file)
Next
End If
FileSystem.GetFiles() returns a collection of file name strings. As OneFineDay showed, you can use the collection's Count property to know if any files were found.
The downside of using FileSystem.GetFile() is that it has to search the entire folder before then returning the entire list of filenames. If you are searching large folders and speed is an issue, consider using Directory.EnumerateFiles() instead. That way, you can output a message if no file was found, otherwise loop throuh the list of found files. For example:
Dim files = Directory.EnumerateFiles("c:\users\zac\desktop\booked vehicle\requested\").GetEnumerator()
If files.MoveNext Then
' files were found
Do
Console.WriteLine(files.Current)
Loop Until Not files.MoveNext
Else
' no files were found
End If
I personally would use Linq to accomplish this. It's very quick and efficient to use in this case. I put the Console.ReadLine() at the end to show the files, you can remove this if need to be. Also you can change the Console.WriteLine to not include the string (s) if you don't want to. The s was declared if you want to show the files and also to see if there are any files. As I said, this was for my viewing to see the files. Straight to the point!
Dim s As String = String.Join(Environment.NewLine, New DirectoryInfo("YOUR DIRECTORY").GetFiles().[Select](Function(file) file.Name).ToArray)
Console.WriteLine(If(s.Length > 0, s, "No files found!"))
Console.ReadLine()
I wrote a program that reads from text files and can create them to load and save data. I have a few files that are the "default" data that are loaded as soon as the program start. The files are loaded by a static reference. My code runs fine before I publish it, but obviously when I publish it, the static references no longer work. I don't know how to add the default data to the build as distinct text files so that I can still reference it after the build.
I imagine being able to build the program and have some sort of folder that accompanies the executable with the default data files in them that I can easily reference, but I don't know how to do that (or if there is a better way).
Below is the start of the code I use to read from the file. Currently, the default data's file name is passed statically into the sub and is used to identify the file to read from, so I'd like to have a published file that I can do the same thing with.
Try
Dim sr As New IO.StreamReader(FileName)
Dim strLine As String = ""
Do Until sr.EndOfStream
strLine = sr.ReadLine
'Code that interprets the data in the file
Note: I've tried adding the files as "Resources" but I can't seem to reference the file as a text file; I can only retrieve the massive wall of text contained within the document which won't work with the above code (unless of course I'm missing something).
If you could clarify:
How do I add a file to a build so that I can still access it
collectively by a file name?
How will my code reference the files (e.g. by
"My.Resources.filename"?) in the final build?
You can add the file to the build as either a content file or an embedded resource.
For a content file, set the Build Action of the file to 'content', and Copy to Output Directory to 'Copy Always' in the file properties. You can then access the file like this:
FileName = Application.StartupPath() = + FileName
Dim sr As New IO.StreamReader(FileName)
...
To embed the file as a resource you have to set the Build Action of the file to 'Embedded Resource' and Copy to Output Directory to false.
This Microsoft support page has a walkthough about accessing embedded resources. The code would be something like this:
Dim sr As StreamReader
Dim thisAssembly As Assembly
thisAssembly = Assembly.GetExecutingAssembly()
sr = New StreamReader(thisAssembly.GetManifestResourceStream("NameSpace." + FileName))
Dim strLine As String = ""
Do Until sr.EndOfStream
strLine = sr.ReadLine
'Code that interprets the data in the file
...
Replace NameSpace with the namespace of your application (Project Properties -> Application -> root namespace)
You also have to add Imports System.Reflection at the top of your code file.
Using an embedded resource has the advantage of less files to manage, and you don't have to keep track of paths.
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 path 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.