Trying to create a good path in vb.net - vb.net

I'm writing an application that creates some text files. I want them in some folders so I did:
Dim fileLoc As String = "c:\users\%username%\downloads\users.txt"
If 1 + 1 = 2 Then <--- not very professional but it works! it works....
Dim fs As FileStream = Nothing
If (Not File.Exists(fileLoc)) Then
fs = File.Create(fileLoc)
Using fs
End Using
End If
End If
If File.Exists(fileLoc) Then
Using sw As StreamWriter = New StreamWriter(fileLoc)
sw.Write(pcname.Text)
End Using
End If
But when I try to debug, the following happens:
DirectoryNotFoundException was unhandled
Cannot find a part of the path (c:\users\%username%\downloads\users.txt)
I'm sure it's because "%username%" because when I fill in the whole path, it works.
But when the program is on another pc it will not work!

try some thing like this
Dim userName as string = WindowsIdentity.GetCurrent().Name;
Dim fileLoc As String = "c:\users\" & userName & "\downloads\users.txt"
If 1 + 1 = 2 Then <--- not very professional but it works! it works....
Dim fs As FileStream = Nothing
If (Not File.Exists(fileLoc)) Then
fs = File.Create(fileLoc)
Using fs
End Using
End If
End If
If File.Exists(fileLoc) Then
Using sw As StreamWriter = New StreamWriter(fileLoc)
sw.Write(pcname.Text)
End Using
End If

I don't think you can use environmental variables like this.
Instead
Dim fileLoc As String = "c:\users\%username%\downloads\users.txt"
Try
Dim fileLoc As String = "c:\users\" & Environment.UserName & "\downloads\users.txt"

Dim fileLoc As String = "c:\users\" & Environment.UserName & "\downloads\users.txt"
If 1 + 1 = 2 Then <--- not very professional but it works! it works....
Dim fs As FileStream = Nothing
If (Not File.Exists(fileLoc)) Then
fs = File.Create(fileLoc)
Using fs
End Using
End If
End If
If File.Exists(fileLoc) Then
Using sw As StreamWriter = New StreamWriter(fileLoc)
sw.Write(pcname.Text)
End Using
End If
This is the correct code! thank you all for thinking with me!

Related

String not recognised in for each loop

If I do the loop and write "ComputerName" arguments, it displays them so that works!
but when I add the actual code I want it to work with it fails, I don't understand why ?
If I run the loop but hard code the ComputerName variable I'm testing with it works i.e. ComputerName = "computer01"
Imports Microsoft.Win32
Module Module1
Sub Main()
'----------------------------------------------------------------------------------------
'to be tested later
'-------------------
'Dim co As New ConnectionOptions
'co.Impersonation = ImpersonationLevel.Impersonate
'co.Authentication = AuthenticationLevel.PacketPrivacy
'co.EnablePrivileges = True
'co.Username = username
'co.Password = password
'Dim scope As New ManagementScope("\\" & machine.Text & "\root\cimv2", co)
'scope.Connect()
'----------------------------------------------------------------------------------------
For Each ComputerName As String In Environment.GetCommandLineArgs()
Dim uninstallKey As String = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"
'Using rk As RegistryKey = Registry.LocalMachine.OpenSubKey(uninstallKey)
Using rk As RegistryKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, ComputerName, RegistryView.Registry64).OpenSubKey(uninstallKey)
Dim Applications As New List(Of String)()
For Each skName As String In rk.GetSubKeyNames()
Using sk As RegistryKey = rk.OpenSubKey(skName)
If Not CStr(sk.GetValue("DisplayName")) = "" Then
Try
Applications.Add(CStr(sk.GetValue("DisplayName")) & " " & CStr(sk.GetValue("DisplayVersion")))
Catch ex As Exception
Console.WriteLine("!!!!!! error: " & ex.Message)
End Try
End If
End Using
Next
Applications.Sort()
For Each app As String In Applications
Console.WriteLine(app)
Next
End Using
Next ComputerName
Console.Write("Press any key to exit . . .")
Console.ReadLine()
End Sub
End Module
I changed this
Sub Main()
For Each ComputerName As String In Environment.GetCommandLineArgs()
to this
Sub Main(args() As String)
For Each ComputerName As String In args
and that seems to work ? any other \ better way I should do it ?

VB.net Crystal report export to html and send as html mail body using outlook

I am trying to send contents of a crystal report as email body using outlook application.
Here is my code in VB.net
Imports outlook = Microsoft.Office.Interop.Outlook
Dim a As String = something.ConnectionString
Dim cryRpt As ReportDocument
Dim username As String = a.Split("=")(3).Split(";")(0) 'get username
Dim password As String = a.Split("=")(4).Split(";")(0) 'get password
cryRpt = New ReportDocument()
Dim Path As String = Application.StartupPath
Dim svPath As String = Application.StartupPath & "\PDF"
If Not Directory.Exists(svPath) Then
Directory.CreateDirectory(svPath)
End If
cryRpt.Load(Path & "\Reports\dr.rpt")
CrystalReportViewer1.ReportSource = cryRpt
cryRpt.SetDatabaseLogon(username, password)
CrystalReportViewer1.Refresh()
Dim myExportOptions As ExportOptions
myExportOptions = cryRpt.ExportOptions
myExportOptions.ExportDestinationType = ExportDestinationType.DiskFile
myExportOptions.ExportFormatType = ExportFormatType.HTML40 'i tried HTML32 also
Dim html40FormatOptions As HTMLFormatOptions = New HTMLFormatOptions()
html40FormatOptions.HTMLBaseFolderName = svPath
html40FormatOptions.HTMLFileName = "dr.htm"
html40FormatOptions.HTMLEnableSeparatedPages = False
html40FormatOptions.HTMLHasPageNavigator = False
html40FormatOptions.UsePageRange = False
myExportOptions.FormatOptions = html40FormatOptions
cryRpt.Export()
Try
Dim oApp As outlook.Application
oApp = New outlook.Application
Dim oMsg As outlook.MailItem
oMsg = oApp.CreateItem(outlook.OlItemType.olMailItem)
oMsg.Subject = txtSubject.Text
oMsg.BodyFormat = outlook.OlBodyFormat.olFormatHTML
oMsg.HTMLBody = ""
oMsg.HTMLBody = getFileAsString(svPath & "\PoPrt\QuotPrt.html")
oMsg.To = txtEmailId.Text
Dim ccArray As New List(Of String)({txtCC1.Text, txtCC2.Text, txtCC3.Text})
Dim cclis As String = String.Join(",", ccArray.Where(Function(ss) Not String.IsNullOrEmpty(ss)))
oMsg.CC = cclis
oMsg.Display(True)
Catch ex As Exception
MsgBox("Something went wrong", vbExclamation)
End Try
SvFormPanel3.Visible = False
the function
Private Function getFileAsString(ByVal file As String) As String
Dim reader As System.IO.FileStream
Try
reader = New System.IO.FileStream(file, IO.FileMode.Open)
Catch e As Exception
MsgBox("Something went wrong. " + e.Message, vbInformation)
End Try
Dim resultString As String = ""
Dim b(1024) As Byte
Dim temp As UTF8Encoding = New UTF8Encoding(True)
Do While reader.Read(b, 0, b.Length) > 0
resultString = resultString & temp.GetString(b)
Array.Clear(b, 0, b.Length)
Loop
reader.Close()
Return resultString
End Function
The report will get exported to the specified location as html. And when we manually open that html file it displays perfectly with border lines and all.
But when its getting added as html body of outlook application, the formatting will be gone, and looks scattered.
can anyone help
Did you try this?
Open outlook, go to, File>Options>Mail
go to section MessageFormat and untick "Reduce message size by removing format..."
I have solved the issue by exporting it into PDF and then convert to Image and embed in email body.

VB.NET - Problems trying to write a textfile

I have problems when trying to delete/create/write to this file.
The error:
The process cannot access the file 'C:\Users\Administrador\AppData\Local\Temp\PlayList_temp.txt' because it is being used by another process.
The highlighted lines by debugger:
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
System.IO.File.Create(Temp_file)
(Any of two, if I delete one line, the other line takes the same error id)
The sub:
Public Sub C1Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not playerargs = Nothing Then
Dim Str As String
Dim Pattern As String = ControlChars.Quote
Dim ArgsArray() As String
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
Dim objWriter As New System.IO.StreamWriter(Temp_file)
Str = Replace(playerargs, " " & ControlChars.Quote, "")
ArgsArray = Split(Str, Pattern)
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
System.IO.File.Create(Temp_file)
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
For Each file In files
' command to writleline
'Console.WriteLine("File Name: {0}", file.Name)
'Console.WriteLine("File Full Name: {0}", file.FullName)
objWriter.Write(file.FullName)
objWriter.Close()
Next
End If
Next
If randomize.Checked = True Then
RandomiseFile(Temp_file)
End If
Process.Start(userSelectedPlayerFilePath, playerargs)
If autoclose.Checked = True Then
Me.Close()
End If
Else
MessageBox.Show("You must select at least one folder...", My.Settings.APPName)
End If
End Sub
First, File.Create creates or overwrite the file specified, so you don't need to Delete it before.
Second, initializing a StreamWriter as you do, blocks the file and therefore you can't recreate it after.
So, simply move the StreamWriter intialization after the File.Create, or better, remove altogether the File.Create and use the StreamWriter overload that overwrites the file
....
If Not playerargs = Nothing Then
....
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
Using objWriter As New System.IO.StreamWriter(Temp_file, false)
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
For Each file In files
' command to writleline
'Console.WriteLine("File Name: {0}", file.Name)
'Console.WriteLine("File Full Name: {0}", file.FullName)
objWriter.Write(file.FullName)
' objWriter.Close()
Next
End If
Next
End Using ' Flush, close and dispose the objWriter
....
Noticed also that you close the writer while still inside the loop, use the Using statement to close correctly the writer after the work is done.
The process cannot access the file 'C:\Users\Administrador\AppData\Local\Temp\PlayList_temp.txt' because it is being used by another process.
That means the file is opened or been used by another process.
Open your task manager and check if the file is there, then close it or simplex end the process.
I have had the same issue but I got it solved by closing the file.
Hope this helps!
From your details it seems that you are willing to delete if file exists and creates a new one.
I would suggest to remove this line:
System.IO.File.Create(Temp_file)
and move this line just over the streamwriter line:
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
Something like this would help you:
Partial code:
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
' Delete file if exists
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
' Create file for write.
Dim objWriter As New System.IO.StreamWriter(Temp_file)
Str = Replace(playerargs, " " & ControlChars.Quote, "")
ArgsArray = Split(Str, Pattern)
...
...
...

ftp file transfer using vb.net without any third party tools

I am writing the code using vb.net for file transfer from remote machine to local machine with out using any third party tools
This my code
Dim reqFTP As FtpWebRequest
Dim filepath As String
Dim filename As String
Dim filename1 As String
Dim ftpserverip As String
Dim ftpuserid As String
Dim ftpPassword As String
Try
filename1 = TxtRemoteFile.Text
filepath = TxtLocalFile.Text
filename = Locfname.Text
ftpserverip = TxtServerIP.Text
ftpuserid = TxtUserName.Text
ftpPassword = TxtPwd.Text
Dim outputStream As FileStream = New FileStream((filepath + ("\\" + filename)), FileMode.Create)
reqFTP = CType(FtpWebRequest.Create(New Uri(("ftp://" _
+ (ftpserverip + ("/" + filename1))))), FtpWebRequest)
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential(ftpuserid, ftpPassword)
Dim response As FtpWebResponse = CType(reqFTP.GetResponse, FtpWebResponse)
outputStream.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
but am getting error like" remote server returned error :(550) fi
I had the same issue. I was not including httpdocs in the remote path.
Example:
ftp://ftp.websitename.com/httpdocs/filenametocopy.txt
System.Net.WebRequest.Create("ftp://ftp.websitename.com/httpdocs/filenametocopy.txt")
Permission was denied because i was trying to write the file outside the root directory.

Using replace method to change password

I am using following code to replace the passwords in my app.config. It replaces successfully but does not reload config file in the memory so datasets give error of wrong password.
Please help
Dim vrTextFind As String = "Password"
Dim vrTextReplaceWith As String = "PWD"
Dim path As String = "D:\VS2008\EncTest\EncTest\bin\Debug\enctest.exe.config"
Dim readText As String = File.ReadAllText(path)
TextBox1.Text = readText
'Find
Dim idx As Integer = 0
idx = TextBox1.Text.IndexOf(vrTextFind, idx)
If idx = -1 Then
MessageBox.Show(vrTextFind & " is not in Textbox1")
Else
TextBox1.SelectionStart = idx
TextBox1.SelectionLength = vrTextFind.Length
End If
'Replace
If TextBox1.Text.Contains(TextBox1.Text) Then
TextBox1.Text = TextBox1.Text.Replace(vrTextFind, vrTextReplaceWith)
Else
MessageBox.Show(TextBox1.Text & " is not in Textbox3")
End If
'''''
'Write all back
File.WriteAllText(path, TextBox1.Text)
'Refreshes the connection string section
ConfigurationManager.RefreshSection("connectionStrings")
In windows application app.config is read only once, when the application starts. If you modify it you will need to restart the app.
Suggestion
Instead of storing password in app.config store it in some other file (like Settings file). Which can be modified and read at runtime. For Settings you can read on MSDN. And choose User-Scope settings.
Hope this helps you.
Instead of using File.WriteallText use the following code to write to app.config:
config.AppSettings.Settings.Item("ConnectionString").Value = TextBox1.Text
config.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("AppSettings")
Then again load the connection string value from app.config.
Dim config As System.Configuration.Configuration
Dim fileMap As New ExeConfigurationFileMap()
fileMap.ExeConfigFilename = "Path of app.config"
config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
' Sets values to config file.
If config.HasFile() Then
strConnString = config.AppSettings.Settings.Item("ConnectionString").Value
End If