IsNothing showing error VB.NET VS2017 Community - vb.net

My first post here and really basic question as I have just started learning.
I am following a step by step tutorial from youtube. https://www.youtube.com/watch?v=6utWyl8agDY code is working alright in the video. below is the code:
Imports System
Imports System.IO
Module Program
Sub Main()
Dim myReader As StreamReader = New StreamReader("values.txt")
Dim line As String = ""
While Not IsNothing(line)
line = myReader.ReadLine()
If Not IsNothing(line) Then
Console.WriteLine(line)
End If
End While
myReader.Close()
Console.ReadLine()
End Sub
End Module
Problem I am facing is that I have red error (squiggly) line under IsNothing. One thing to note is the in the video tutorial version of VS under use is 2013 while I am using VS2017 community. any idea what I am doing wrong here?

I'm not sure what your tutorial says but there are issues with that code. It's fairly poorly structured and, to be honest, you shouldn't really use IsNothing anyway. The most immediate issue is where you're reading the text and that you're testing for Nothing twice. The code would be better written like this:
Dim myReader As New StreamReader("values.txt")
Dim line As String = myReader.ReadLine()
While line IsNot Nothing
Console.WriteLine(line)
line = myReader.ReadLine()
End While
myReader.Close()
Console.ReadLine()
Comparing directly to Nothing using Is or IsNot is the way to go and there's also no need for that check inside the loop.
If you want to get a bit more advanced, you can also create the StreamReader with a Using statement, so it gets closed implicitly:
Using myReader As New StreamReader("values.txt")
Dim line As String = myReader.ReadLine()
While line IsNot Nothing
Console.WriteLine(line)
line = myReader.ReadLine()
End While
End Using
Console.ReadLine()
Better still would be to not create the StreamReader yourself at all but let the Framework do that for you:
For Each line As String In File.ReadLines("values.txt")
Console.WriteLine(line)
End Using
Console.ReadLine()
Note that that code uses ReadLines rather than ReadAllLines. Both would work but the former will only read one line at a time while the latter will read the whole file first, load the lines into an array and return that. In this case it probably doesn't really matter which you use but ReadLines is generally preferable unless you specifically need all the lines first or you want to loop over them multiple times.

You have to decide whether your console application requires .net Core or .net Framework is sufficient.
As others have written in responses, your code is in need of improvement.
However, your code will run correctly if you choose the .net framework for your new project in Visual Studio 2017 Community as shown in the screenshot below.

Related

Receiving an error from trying to make a startup program shortcut

I am trying to make a shortcut for my program so that it starts automatically with windows. The following code is the sub that creates the shortcut and how it gets it's variables but it fails.
Dim ShortCutPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup) & "/ScreenRot.lnk"
Shared Sub CreateShortCut(File As String, ShortCutPath As String)
Dim oShell As Object
Dim oLink As Object
'you don’t need to import anything in the project reference to create the Shell Object
Try
oShell = CreateObject("WScript.Shell")
oLink = oShell.CreateShortcut(ShortCutPath)
oLink.IconLocation = File
oLink.TargetPath = File
oLink.Arguments = ""
oLink.WindowStyle = 1
oLink.Save()
Catch ex As Exception
End Try
End Sub
The line it seems to fail on is.
oLink = oShell.CreateShortcut(ShortCutPath)
The error I am getting is
DirectCast(ex, System.MissingMemberException).Message
Public member 'CreateShortcut' on type 'IWshShell3' not found.
I am using this in my program.
Imports IWshRuntimeLibrary
I have tried a couple different ways to make the shortcut but this seems to be the one that should work for what I need. I've read a bit about using this code and watched a video but nothing talks about the error. I've googled the error but nothing resembles a solution. I've tried to adjust the code slightly by using other examples but it still fails with more or less the same error. I don't really understand what the error is saying, so I can try and figure it out. thanks for your time and any help you guys can give.
After reviewing many posts and trying a lot of different things I found a solution on Stackoverflow which I can confirm actually works.
Stackoverflow Post
This post has the solution, hopefully it helps other people with this problem.

Cannot save a freshly created bmp file, help needed

Hate to sound like a broken record, but I simply cannot get the program I wrote in Visual Basic to write a file when run standalone; but it works fine when run via the debugger.
Simplified, the code looks like this (and the bitmap image is being created and is being saved, i.e., the file does not already exist):
Using bmp As New Bitmap(imgHorSize, imgVerSize) ‘ the sizes are not too large
<build the bitmap>
Dim fName As String = “C:\Users\<name>\Desktop\temp\foobar.jpg"
bmp.Save(fName, ImageFormat.Jpeg)
End Using
When I run this outside the debugger, I get
System.UnauthorizedAccessException: Access to the path
'C:\Users<name>\Desktop\temp\foobar.jpg' is denied
I saw some notes that suggest there should be a \\ after C:. Other sources show using a / instead of a \. Not sure that either really matters (since the directory name is coming from the result of a FolderBrowserDialog). I have checked the folder permissions on temp and see that my account has full control. I added user Everyone, via the security tab, and gave it full control. Same problem. As an experiment, I changed the above code to
Using bmp As New Bitmap(imgHorSize, imgVerSize)
<build the bitmap>
Dim fName As String = “C:\Users\<name>\Desktop\temp\foobar.jpg"
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter(fName, True)
file.WriteLine("Here is the first string.")
End Using
and I got the exact same error. I also tried creating a MemoryStream, but that also didn’t work.
So, the issue is probably not related to the bmp.Save process, but something more fundamental. I have been looking at various things and have tried a few of them, but nothing works. This should be super easy to do, so what am I doing wrong?
== follow up ==
To come up with something to share in its entirety, I just wrote the following, very simple program that basically does the same as the real program:
Imports System.Drawing
Imports System.Drawing.Imaging
Public Class Form1
Structure myImages
Dim strFName As String
Dim imgL As Image
End Structure
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim imgLI As myImages
imgLI.strFName = "C:\Users\<username>\Desktop\EinRiddle\ItemImages\An_Cat.jpg"
imgLI.imgL = New Bitmap(Image.FromFile(imgLI.strFName), 150, 150)
Dim bmp As New Bitmap(300, 400)
Using bmp
Dim gr As Graphics = Graphics.FromImage(bmp)
gr.Clear(Color.WhiteSmoke)
gr.DrawImage(imgLI.imgL, 20, 20)
bmp.Save("C:\Users\<username>\Desktop\testImg.jpg", ImageFormat.Jpeg)
gr.Dispose()
End Using
Application.Exit()
End
End Sub
End Class
I am getting the same error message...
Have you tried another directory? Often one cannot write a file to the desktop.
Have you tried another format (for example ImageFormat.Bmp)?
You use “ instead of " ... Is that the mistake? Ah, I guess this is not the real code and you wrote this from memory and and something made “
Sometimes it takes a while before the picture and graphics can be disposed because the image is saved lazily. Even if this is not welcomed, give it a try
bmp.Save("C:\Users\<username>\Desktop\testImg.jpg", ImageFormat.Jpeg)
Application.DoEvents()
gr.Dispose()
End Using
I found the answer: On this computer, my user files are on the D: drive. Thus, when I changed the path from C: to D:, it worked. Of course, why this is necessary, since there is symbolic link, I don't understand...

StringBuilder in .net not writing entire file

I'm trying to write a text file. Here's my main,slightly clipped for clarity:
Private Sub WriteProperty(FilePath As String)
Try
SB = New StringBuilder
WriteConfig()
'a bunch of methods similar to WriteConfig here...
Dim File As New System.IO.StreamWriter(FilePath)
File.WriteLine(SB.ToString())
Catch ex As Exception
Dim X As Integer = 5 'cheesy way to add a breakpoint
End Try
End Sub
And here is one of about a dozen subs that add text to the file:
Private Sub WriteConfig()
Dim TempSB As New StringBuilder
TempSB.AppendLine("[CONFIG]")
TempSB.AppendLine("[END_CONFIG]")
TempSB.AppendLine("")
SB.Append(TempSB)
End Sub
There are about a dozen methods that add things like this, most of them add about 2k of text instead of the couple of lines in this example. When I examine SB in the debugger the total result is a little over 15k long. But when I open the file, it's 12k, and the end is all missing - it cuts off in the middle of one of the strings. There is no exception raised.
I know SB has problems with lots of little appends, which is why I used the TempSB's in the subs, but it has the exact same problem, and if I add them directly to SB instead the only difference is the "break" occurs a few characters earlier.
Can anyone offer a suggestion as to what might be happening?
StreamWriter uses an internal buffer. You need to Close() your StreamWriter to force it to write the remaining buffered data to the file. Better yet, wrap it in a Using statement. That will call its Dispose(), which in turn calls its Close().
Using File As New System.IO.StreamWriter(FilePath)
File.WriteLine(SB.ToString())
End Using
There's a convenience method that will do this for you in a single line:
System.IO.File.WriteAllText(FilePath, SB.ToString())

inserting data from a text file to textboxes and setting combobox indecies

so I am writing a program and trying to setup the save/open features of the program. I have the Save feature working just fine, but can't get the open feature to work.
The issue I'm running into is pulling the data from the text file to the form to fill in the multiple fields and controls. my example code is below
Imports System.IO
Main 1
Sub openFile_Click(sender, e) handles openFile.Click
Dim lineIndex As Integer = 12 'this is my total lines in my file
ofdRead.ShowDialog()
If ofdRead.FileName <> "" then
sr = New StreamReader(ofdRead.FileName)
For i As Integer = 0 To lineIndex -1
sr.ReadLine()
Next
txtField1.Text = sr.ReadLine
cboBox1.SelectedIndex = sr.ReadLine
'this continues through all fields til complete
sr.Close()
End If
End Sub
End Class
I keep getting an error for anything that is being returned as not being a string, and it seems as though the data is being read in reverse as well according to my error output.
Any help would be much appreciated (been searching and pouring over forums for 2 days looking for help)
Thanks Tim Schmelter for your insight. I was calling the wrong data type for the cboBox1 variable. Here is my corrected code (without the For-Loop, turns out i didn't need it)
cboBox1.SelectedItem = sr.ReadLine
so everytime I run into something like that I just have to tell it to put it in as a string instead of an integer

VB can't string to arraylist when read from file

Either I'm missing something really obvious or something about vb is really messed up. I'm trying to read in from a file and add the lines to an arraylist... pretty simple If I add strings to the arraylist this way
selectOptions.Add("Standard")
selectOptions.Add("Priority")
selectOptions.Add("3-Day")
selectOptions.Add("Overnight")
I have no problems
But when I do this it appears to end up empty which makes no sense to me.
Dim reader As StreamReader = My.Computer.FileSystem.OpenTextFileReader(path)
Dim line As String
Do
line = reader.ReadLine
selectOptions.Add(line)
Loop Until line Is Nothing
reader.Close()
Messagebox.show line all day so I know it is reading the file and the file isn't empty and I have checked the type of line which comes back as string. This makes no sense to me.
Checking for reader.EndOfStream in a While loop will probably work better:
Dim reader As New StreamReader(path)
Dim line As String
While Not reader.EndOfStream
line = reader.ReadLine
selectOptions.Add(line)
End While
reader.Close()
You can also get an exception if selectOptions isn't declared as a New ArrayList, if you properly have all your Options turned On.
Another thing to remember, if your code is in the form's Load Handler, it won't throw an exception it will just break out of the handler routine and load the form. This makes it really hard to find things like bad file names, badly declared objects, etc.
One thing I do is put suspect code in a button's Click handler and see what exceptions it throws there.
Of course this could all be moot if you use the File.ReadAllLines method and add it directly to the ArrayList:
selectOptions.AddRange(File.ReadAllLines(path))