how do I use a document using debug folder (vb.net) - vb.net

I am trying to show a document (called zzz.txt so it appears at the bottom) in a text box, and I have put it in the debug folder (TextViewerthingy > obj > Debug) and have used CurDir() & "\zzz.txt" for the location, which apparently is not correct. I have used this correctly with other projects
Dim filename As String = CurDir() & "\zzz.txt"
Dim ObjReader As New System.IO.StreamReader(filename)
gives me an error saying the file is not there. This is the location, what is it that I'm doing wrong in this case?
C:\Users\Notshowingmyname\source\repos\TextViewerthingy\TextViewerthingy\bin\Debug

Try this one :
Imports System.IO
Dim filename as string = Directory.GetCurrentDirectory() + "\zzz.txt"
Or second alternative :
filename = My.Computer.FileSystem.CurrentDirectory + "\zzz.txt"
Make sure file name and extensions are correct.

Related

Add a path to a code VB.net / visual basic

how do I add a path to a code where "HERE_HAS_TO_BE_A_PATH" is. When I do, Im getting an error message. The goal is to be able to specific the path where is the final text file saved.
Thanks!
Here is a code:
Dim newFile As IO.StreamWriter = IO.File.CreateText("HERE_HAS_TO_BE_A_PATH")
Dim fix As String
fix = My.Computer.FileSystem.ReadAllText("C:\test.txt")
fix = Replace(fix, ",", ".")
My.Computer.FileSystem.WriteAllText("C:\test.txt", fix, False)
Dim query = From data In IO.File.ReadAllLines("C:\test.txt")
Let name As String = data.Split(" ")(0)
Let x As Decimal = data.Split(" ")(1)
Let y As Decimal = data.Split(" ")(2)
Let z As Decimal = data.Split(" ")(3)
Select name & " " & x & "," & y & "," & z
For i As Integer = 0 To query.Count - 1
newFile.WriteLine(query(i))
Next
newFile.Close()
1) Use a literal string:
The easiest way is replacing "HERE_HAS_TO_BE_A_PATH" with the literal path to desired output target, so overwriting it with "C:\output.txt":
Dim newFile As IO.StreamWriter = IO.File.CreateText("C:\output.txt")
2) Check permissions and read/write file references are correct:
There's a few reasons why you might be having difficulties, if you're trying to read and write into the root C:\ directory you might be having permissions issues.
Also, go line by line to make sure that the input and output files are correct every time you are using one or the other.
3) Make sure the implicit path is correct for non-fully qualified paths:
Next, when you test run the program, it's not actually in the same folder as the project folder, in case you're using a relative path, it's in a subfolder "\bin\debug", so for a project named [ProjectName], it compiles into this folder by default:
C:\path\to\[ProjectName]\bin\Debug\Program.exe
In other words, if you are trying to type in a path name as a string to save the file to and you don't specify the full path name starting from the C:\ drive, like "output.txt" instead of "C:\output.txt", it's saving it here:
C:\path\to\[ProjectName]\bin\Debug\output.txt
To find out exactly what paths it's defaulting to, in .Net Framework you can check against these:
Application.ExecutablePath
Application.StartupPath
4) Get user input via SaveFileDialogue
In addition to a literal string ("C:\output.txt") if you want the user to provide input, since it looks like you're using .Net Framework (as opposed to .Net Core, etc.), the easiest way to set a file name to use in your program is using the built-in SaveFileDialogue object in System.Windows.Forms (like you see whenever you try to save a file with most programs), you can do so really quickly like so:
Dim SFD As New SaveFileDialog
SFD.Filter = "Text Files|*.txt"
SFD.ShowDialog()
' For reuse, storing file path to string
Dim myFilePath As String = SFD.FileName
Dim newFile As IO.StreamWriter = IO.File.CreateText(myFilePath) ' path var
' Do the rest of your code here
newFile.Close()
5) Get user input via console
In case you ever want to get a path in .Net Core, i.e. with a console, the Main process by default accepts a String array called args(), here's a different version that lets the user add a path as the first parameter when running the program, or if one is not provided it asks the user for input:
Console.WriteLine("Hello World!")
Dim myFilePath = ""
If args.Length > 0 Then
myFilePath = args(0)
End If
If myFilePath = "" Then
Console.WriteLine("No file name provided, please input file name:")
While (myFilePath = "")
Console.Write("File and Path: ")
myFilePath = Console.ReadLine()
End While
End If
Dim newFile As IO.StreamWriter = IO.File.CreateText(myFilePath) ' path var
' Do the rest of your code here
newFile.Close()
6) Best practices: Close & Dispose vs. Using Blocks
In order to keep the code as similar to yours as possible, I tried to change only the pieces that needed changing. Vikyath Rao and Mary respectively pointed out a simplified way to declare it as well as a common best practice.
For more information, check out these helpful explanations:
Can any one explain why StreamWriter is an Unmanaged Resource. and
Should I call Close() or Dispose() for stream objects?
In summary, although streams are managed and should garbage collect automatically, due to working with the file system unmanaged resources get involved, which is the primary reason why it's a good idea to manually dispose of the object. Your ".close()" does this. Overrides for both the StreamReader and StreamWriter classes call the ".dispose()" method, however it is still common practice to use a Using .. End Using block to avoid "running with scissors" as Enigmativity puts it in his post, in other words it makes sure that you don't go off somewhere else in the program and forget to dispose of the open filestream.
Within your program, you could simply replace the "Dim newFile As IO.StreamWriter = IO.File.CreateText("C:\output.txt")" and "newFile.close()" lines with the opening and closing statements for the Using block while using the simplified syntax, like so:
'Dim newFile As IO.StreamWriter = IO.File.CreateText(myFilePath) ' old
Using newFile As New IO.StreamWriter(myFilePath) ' new
Dim fix As String = "Text from somewhere!"
newFile.WriteLine(fix)
' other similar operations here
End Using ' new -- ensures disposal
'newFile.Close() ' old
You can write that in this way. The stream writer automatically creates the file.
Dim newFile As New StreamWriter(HERE_HAS_TO_BE_A_PATH)
PS: I cannot mention all these in the comment section as I have reputations less than 50, so I wrote my answer. Please feel free to tell me if its wrong
regards,
vikyath

Delete A File That Contains The App Name (VB.NET)

This is the code I'm Using:
Dim file As String
Dim prefetchPath As String
Dim FileName As String = My.Application.Info.AssemblyName
prefetchPath = Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine) & "\Prefetch"
For Each file In IO.Directory.GetFiles(prefetchPath)
If file.Contains(FileName) Then
IO.File.Delete(file)
End If
Next
i don't know why it does not work if i use FileName. But it work if i use this code
If file.Contains("Example.exe") Then
IO.File.Delete(file)
End If
I want to make sure that if someone changes the name of the application the code works the same way(I already running the file as Administrator)
Help me Thanks.
My guess is that AssemblyName only returns the name without the extension, try including the .exe. Also, it is worth noting that you can use the IO.DirectoryInfo class and pass the file name in the GetFiles method to cut out your For/Each loop.
Here is a quick example:
Dim prefetchPath As String = IO.Path.Combine(Environment.GetEnvironmentVariable("windir", EnvironmentVariableTarget.Machine), "Prefetch")
Dim FileName As String = My.Application.Info.AssemblyName & ".exe"
If New IO.DirectoryInfo(prefetchPath).GetFiles(FileName).Count > 0 Then
IO.File.Delete(IO.Path.Combine(prefetchPath, FileName))
End If

copy file to directory in visual basic vb.net

I am tringing to copy files settings.copy from sourceDir to backupDir but getting error
Dim sourceDir As String = "c:\in\settings.copy"
Dim backupDir As String = "c:\out\"
File.Copy(sourceDir, backupDir)
while executing above script getting below error
System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'c:\out\'.'
I already created c:\out\ folder
Have you read the documentation for File.Copy, or even just paid attention to Intellisense? Both arguments must be file paths. Neither can be folder paths.
On a related note, why do you have a variable named 'sourceDir' when it's clearly a file path and not a directory path? If you name things clearly - and particularly not misleadingly - then it's more likely that you'll avoid such mistakes. Of course, using the Help menu or F1 key to confirm that you're using a type of method correctly would help too.
Dim userprofile As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
Dim SystemDir As String = Environment.GetEnvironmentVariable("SystemDrive")
Dim sourceDir As String = "y\inbound\settings.exe"
Dim backupDir As String = "AppData\Local\user\default_user\"
Dim root As String = Path.GetPathRoot(userprofile)
Dim useDrpath As String = Path.Combine(userprofile, backupDir)
Dim SysDrpath As String = Path.Combine(SystemDir, root, sourceDir)
Dim file = New FileInfo("settings.cps")
file.CopyTo(Path.Combine(SysDrpath, useDrpath, file.Name), True)
My gole is to copy file from system installed driver to user profile driver
with above code i am able to copy file
c:\y\inbound\settings.exe C:\Users\pavan\AppData\Local\user\default_user\
please suggested any other better way to do above

Cannot retrieve path of Special Folders when redirection enabled

I have a tool that reads a .txt file for a list of paths and uses them in a copy. It looks like this:
***DESTINATION***
E:\Backup
***Sources***
%USERPROFILE%\Pictures
%USERPROFILE%\Favourites
%USERPROFILE%\Contacts
%USERPROFILE%\My Videos
My system has folder redirection enabled so 'Pictures' for example is actually D:\Adam\Pictures. However when using the following code it will only resolve as C:\Adam\Pictures and throw a "Cannot find path error".
'Declarations earlier in script
Dim Destpath As String = System.IO.File.ReadAllLines(Application.StartupPath + "\CONFIG.txt")(1)
Dim userprofilevar = (Environment.GetFolderPath(Environment.SpecialFolder.UserProfile))
'Snippet of line reading logic
ElseIf line.Contains("%USERPROFILE%") Then
Dim lineArray() As String = line.Split("\")
Dim lineuser As String = userprofilevar + "\"
Dim linepath As String = lineArray(1)
line = lineuser + linepath
Destpath = String.Concat(Destpath, "\", linepath)
MessageBox.Show(Destpath)
Else
Does anyone know how to resolve the correct path of the redirected folder through the %USERPROFILE% variable?
Solution I found:
After converting #AlexB's example into VB.NET and getting it working in my app, I simply declared each of the %Userprofile% folders as a string then have the line reading logic update the line string as the correct folder path:
'Declarations as start of Form
Dim downloadsPath As String = KnownFolders.GetPath(KnownFolder.Downloads)
Dim contactspath As String = KnownFolders.GetPath(KnownFolder.Contacts)
'Snippit of line reading logic
ElseIf line.Contains("%USERPROFILE%\Downloads") Then
line = downloadspath
ElseIf line.Contains("%USERPROFILE%\Contacts") Then
line = contactspath
It's not pretty to do for all 11 %Userprofile% folders, but it works!

How to get the full path of a file through the file's name

I am trying to get the path of a file from the name of it. I made an executable file on my desktop, Commands.exe, I am trying to get the full path of it through a console application. I want the program to search the whole of my computer for the file, (it is on my desktop for simplicity) and return the path, bearing in mind the file could be anywhere. The path I want the program to return is:
"C:\Users\Jimbob\Desktop\Commands.exe"
My Code:
Imports System.IO
Module Module1
Dim fileLocation As String
Dim filename As String = "Commands.exe"
Sub Main()
fileLocation = Path.GetFullPath(filename)
Console.WriteLine(fileLocation)
Console.ReadLine()
End Sub
End Module
but instead it prints out
"C:\Users\Jimbob\Documents\Visual Studio 2012\Projects\get path
test\get path test\bin\Debug\Commands.exe"
It prints out the path of the project all of my code is in. In this path, there isn't even a Commands.exe in the Debug folder.
Help?
or couldn't you just
dim fileName as string = My.Application.Info.DirectoryPath() & "\Commands.exe"
You can use the Directory.GetFiles or the FileSystem.GetFiles methods to do this.
Something along the lines of:
fileLocation = My.Computer.FileSystem.GetFiles("C:\",
FileIO.SearchOption.SearchAllSubDirectories,
filename)(0)