I'm creating a code for the computers at work. I had to make an "Install" program. I didn't know how to do it properly but I found a way to do it.
When I "Install" the program on a other computer I have my USB-stick and copy it to the local disk at the computer.
Now I start the program for the first time at their computer and this code run's
and then I got an error here because Program is not yet divined:
Dim lMateriaalCertificaat As String = System.IO.File.ReadAllText(Program & "Materialen&Certificaten.txt")
Dim Pathproj As String = AppDomain.CurrentDomain.BaseDirectory
Dim Pathfile As String = Pathproj.Replace("bin\Debug\", "Bestanden\Locatie.txt")
Dim Program As String = System.IO.File.ReadAllText(Pathfile)
'Deze bestanden worden aangemaakt en er wordt automatisch een route ingezet.
Dim lMateriaalCertificaat As String = System.IO.File.ReadAllText(Program & "Materialen&Certificaten.txt")
Dim lBibliotheek As String = System.IO.File.ReadAllText(Program & "Bibliotheek.txt")
Dim lExcel_autonummering As String = System.IO.File.ReadAllText(Program & "Excelbestand autonummering.txt")
Dim lLocatie_telbestanden As String = System.IO.File.ReadAllText(Program & "Locatie telbestanden.txt")
Dim lMapnamen As String = System.IO.File.ReadAllText(Program & "Mapnamen.txt")
Dim lOrderschijf As String = System.IO.File.ReadAllText(Program & "Zoek schijf.txt")
Because when the form2_load I do this and then I wan't to divine that string.
Public Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim Locatie_05Kuipers As String
If System.IO.File.ReadAllText(Pathfile) = "" Then
'If System.IO.File.ReadAllText("C:\testing1\testing2\testing7\testing1\testing1\text.txt") = "" Then
Locatie_05Kuipers = InputBox("Vul hier de Locatie waar je start bestanden moeten staan. Bijvoorbeeld: K:\Inventor\Instalprogram\ ")
If System.IO.File.Exists(Pathfile) Then
System.IO.File.Delete(Pathfile)
End If
Dim objStreamWriter As StreamWriter
objStreamWriter = New StreamWriter(Pathfile)
objStreamWriter.WriteLine(Locatie_05Kuipers & "\03 - Locaties")
objStreamWriter.Close()
ButtonInstal.Visible = True
Exit Sub
Else
End If
So how or where do I need to put my strings?
You can save a path in your settings, and every time you need it, you can create the file and put your data in it.
For example:
Dim pathString As String = My.Settings.filePath
Dim fullPath = Path.Combine(pathString, "Locatie.txt")
If Not Directory.Exists(pathString) Then
Directory.CreateDirectory(pathString)
File.Create(fullPath)
Else
If Not File.Exists(pathString) Then
File.Create(fullPath)
Else
Console.WriteLine($"File {fullPath}already exists.")
End If
End If
good morning everyone
I`m having a little issue with a dgv. Im trying to fill it with the result of a function that shows the name of the files in a folder and the amount of lines each file has.
But for some reason im having a null vaule on the datagrid and i dont know how to remove it. I`ve been doing this without much knowledge of vb.net or coding whatsoever so any help would be greatly apreciated
Here is the code:
Imports System
Imports System.Linq
Imports System.Collections
Imports System.IO
Imports System.IO.StreamReader
Imports System.IO.DirectoryInfo
Public Class MainForm
'asigna la var como datatable
Dim results1 As New DataTable
Private Sub Boton_Buscar_Click(sender As System.Object, e As System.EventArgs) Handles Boton_Buscar.Click
'muestra el dialogo y guarda el dir
FBD1.ShowDialog()
TextBox1.Text = FBD1.SelectedPath
FSW1.Path = TextBox1.Text
'indica el datasource al datagrid
Try
DGV1.DataSource = GetLineCount()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
'devuelve archivos y su num de lineas
Public Function GetLineCount() As DataTable
results1.Columns.Add(0)
results1.Columns.Add(1)
'array para los tipos de archivo
Dim MyFileArray As [String]() = New [String](7) {"*.txt", "*.doc", "*.docx", "*.odt", "*.pdf", "*.rtf", _
"*.csv", "*.vb"}
'array para los directorios
Dim MyDirectoryArray As [String]() = New [String](0) {TextBox1.Text}
' loop directorios
For Each sd As [String] In MyDirectoryArray
Dim dir As New DirectoryInfo(sd)
'loop los tipos de archivos
For Each sFileType As [String] In MyFileArray
'loop los archivos ante el contador
For Each file__1 As FileInfo In dir.GetFiles(sFileType)
Dim LineCount = System.IO.File.ReadAllLines(file__1.FullName).Count()
'alimenta el datagrid con los datos nuevos
results1.Rows.Add()
results1.Rows.Add.Item(0) = "FileName: " & file__1.FullName
results1.Rows.Add.Item(1) = "LineCount: " & LineCount
Next
Next
Next
Return results1
End Function
End Class
And here is the output im getting:
Any help is very welcome, have a good day
The reason you are getting null values is that you're trying to add the row by one cell at a time.
Instead of
results1.Rows.Add()
results1.Rows.Add.Item(0) = "FileName: " & file__1.FullName
results1.Rows.Add.Item(1) = "LineCount: " & LineCount
Try
results1.Rows.Add("FileName: " & file__1.FullName, "LineCount: " & LineCount)
Your current code adds three rows instead of 1 each time: first an empty row, then a row with cell(0) filled and then null, and then a row with null and then cell(1) filled.
I'm having problems with my code, the idea is to find a file in a folder but this is a remote folder and it has many sub folders if it doesn't find it then it should look for it in another folder, but it doesn't seem to work could anyone help me please? thanks for any help :).
Dim dt2 As New System.Data.DataTable()
Dim query2 As String = "SELECT juzgado, rutaPDF FROM mismoCorreo WHERE DATEPART(DAY, BirthDate) = #Day AND DATEPART(MONTH, BirthDate) = #Month"
Dim constr2 As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr2)
Using cmd As New SqlCommand(query2)
cmd.Connection = con
cmd.Parameters.AddWithValue("#Day", DateTime.Today.Day)
cmd.Parameters.AddWithValue("#Month", DateTime.Today.Month)
Using sda As New SqlDataAdapter(cmd)
sda.Fill(dt2)
End Using
End Using
End Using
For Each row As DataRow In dt2.Rows
Dim juzgado As String = row("juzgado").ToString()
Dim nombre_archivo As String = row("rutaPDF").ToString()
If (juzgado = "PRIMERO DE LO FAMILIAR") Then
enviar = "\\172.16.20.101\SisInt\Juzgados\acuerdos\J92016SEM2" & "\" & nombre_archivo & ".docx"
ElseIf (juzgado = "SEGUNDO DE LO FAMILIAR") Then
enviar = "\\172.16.20.101\SisInt\Juzgados\acuerdos\J102016SEM2" & "\" & nombre_archivo & ".docx"
End If
Next
For index = 0 To ListaArchivos.Count - 1
Dim wordApplication = New Microsoft.Office.Interop.Word.Application()
Dim wordDocument As Document = Nothing
Dim paramSourceDocPath As String = ListaArchivos.Item(index)
Dim paramExportFilePath As String = "\\172.16.20.101\SisInt\Convertidos" + "\" + ListaNombres.Item(index) + ".pdf"
Dim paramExportFormat As WdExportFormat =
WdExportFormat.wdExportFormatPDF
Dim paramOpenAfterExport As Boolean = False
Dim paramExportOptimizeFor As WdExportOptimizeFor =
WdExportOptimizeFor.wdExportOptimizeForPrint
Dim paramExportRange As WdExportRange =
WdExportRange.wdExportAllDocument
Dim paramStartPage As Int32 = 0
Dim paramEndPage As Int32 = 0
Dim paramExportItem As WdExportItem =
WdExportItem.wdExportDocumentContent
Dim paramIncludeDocProps As Boolean = True
Dim paramKeepIRM As Boolean = True
Dim paramCreateBookmarks As WdExportCreateBookmarks =
WdExportCreateBookmarks.wdExportCreateWordBookmarks
Dim paramDocStructureTags As Boolean = True
Dim paramBitmapMissingFonts As Boolean = True
Dim paramUseISO19005_1 As Boolean = False
Try
'Abrir documento basados en el que selecciono
wordDocument = wordApplication.Documents.Open(paramSourceDocPath)
' Exportar al formato deseado
If Not wordDocument Is Nothing Then
wordDocument.ExportAsFixedFormat(paramExportFilePath,
paramExportFormat, paramOpenAfterExport,
paramExportOptimizeFor, paramExportRange, paramStartPage,
paramEndPage, paramExportItem, paramIncludeDocProps,
paramKeepIRM, paramCreateBookmarks,
paramDocStructureTags, paramBitmapMissingFonts,
paramUseISO19005_1)
End If
Catch ex As Exception
'MessageBox.Show(ex.Message)
'Registro en base de datos fecha hora y ex.message
Finally
If Not wordDocument Is Nothing Then
wordDocument.Close(False)
wordDocument = Nothing
End If
If Not wordApplication Is Nothing Then
wordApplication.Quit()
wordApplication = Nothing
End If
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
End Try
Next
I will be very grateful for your help on this.
I am trying to populate a treeview to show only a directory as its main root and its sub directories. Other codes and tutorials online show drives and other special folders.
I wan to show only a folder path like:
C:\Main Folder\Subdirectory1\Subdirectory2 etc. in the nodes
This is all I have and its not helping.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs)
'Get a list of drives
Dim drives As DriveInfo() = DriveInfo.GetDrives()
Dim rootDir As String = String.Empty
'Now loop thru each drive and populate the treeview
For i As Integer = 0 To drives.Length - 1
rootDir = drives(i).Name
'Add this drive as a root node
TreeView1.Nodes.Add(rootDir)
'Populate this root node
PopulateTreeView(rootDir, TreeView1.Nodes(i))
Next
End Sub
Private Sub PopulateTreeView(dir As String, parentNode As TreeNode)
Dim folder As String = String.Empty
Try
Dim folders As String() = System.IO.Directory.GetDirectories(dir)
If folders.Length <> 0 Then
Dim childNode As TreeNode = Nothing
For Each folder_loopVariable As String In folders
folder = folder_loopVariable
childNode = New TreeNode(folder)
childNode.Nodes.Add("")
parentNode.Nodes.Add(childNode)
Next
End If
Dim files As String() = System.IO.Directory.GetFiles(dir)
If files.Length <> 0 Then
Dim childNode As TreeNode = Nothing
For Each file As String In files
childNode = New TreeNode(file)
parentNode.Nodes.Add(childNode)
Next
End If
Catch ex As UnauthorizedAccessException
parentNode.Nodes.Add(folder & Convert.ToString(": Access Denied"))
End Try
End Sub
He tomado como base tu código y he hecho algunas modificaciones para poder adaptarlo a mis necesidades.
Si necesitas crear una lista de todos los archivos por unidades, la funcion ActualizaTV es la encargada de Actualizar el TreeView que, en mi caso, se llama tvDir
Te dejo el resultado por si te viene bien:
Sub ActualizaTV(workpath As String)
If workpath Is Nothing Then Exit Sub
With tvDir
.Nodes.Clear()
'Creating the root node
.Nodes.Add(New TreeNode(workpath))
PopulateTreeView(workpath, .Nodes(0))
End With
End Sub
Sub PopulateTreeView(dir As String, parentNode As TreeNode)
Try
'Se añada en primer lugar los archivos del directorio
For Each file In System.IO.Directory.GetFiles(dir)
If file.Length = 0 Then Continue For
parentNode.Nodes.Add(New TreeNode(file.Replace(dir & "\", "")))
Next
'Se buscan las posibles carpetas nuevas del directorio y se añadem
For Each folder As String In System.IO.Directory.GetDirectories(dir)
If folder.Length = 0 Then Continue For
parentNode.Nodes.Add(New TreeNode(folder))
'En caso de que haya subcarpetas, se repite la operación
If UBound(System.IO.Directory.GetDirectories(folder)) > 0 Or _
UBound(System.IO.Directory.GetFiles(folder)) > 0 Then _
PopulateTreeView(folder, parentNode.LastNode)
Next
Catch ex As UnauthorizedAccessException
parentNode.Nodes.Add(dir & Convert.ToString(": Access Denied"))
End Try
End Sub
Un saludo
I have a VB.NET script that creates mail accounts using smartermail webservice, i know nothing of VB.Net but i have a little knowledge of programming. I created a new project on Visual Studio 2012 and know i need to call the function that creates the accounts on the main module to run it, that's a console app project.
Main Module (Module1.vb) is as follows:
Module Module1
Sub Main()
End Sub
End Module*
My function is:
Sub fnc_CriaContas_Email_Lote()
It's on the file cria_contas_lote.vb in the same directory.
Content of cria_contas_lote.vb:
Sub fnc_CriaContas_Email_Lote()
Dim oPainelWS As PainelControle.svcSmarterMail
Dim sRetorno As String = ""
Try
'oPainelWS = New PainelControle.svcSmarterMail("xxx.xxx.xxx.xxx")
Catch ex As Exception
Console.WriteLine("Erro ao efetuar a conexão no servidor remoto: " & ex.Message)
Exit Sub
End Try
Dim sNomeArquivo As String = "C:\dir\emails.xlsx"
Dim sSQL As String = ""
Dim stringExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sNomeArquivo & ";Extended Properties=Excel 12.0"
Dim oExcel As New OleDbConnection(stringExcel)
Try
oExcel.Open()
Catch ex As Exception
Console.Write("O arquivo não foi localizado ou ocorreu um erro de abertura no servidor. Arquivo: " & sNomeArquivo)
Console.Write(vbCrLf & "================================================")
Console.Write(vbCrLf & ex.Message)
Console.Write(vbCrLf & "================================================")
Exit Sub
End Try
Dim oDataSet As New DataSet
Try
Dim oExcelAdapter As New OleDbDataAdapter("select * from [contas_pop$]", oExcel)
oExcelAdapter.Fill(oDataSet, "conteudo")
Catch ex As Exception
Console.Write("A tabela CONTAS_POP não foi localizada. Renomeie sua WorkSheet para CONTAS_POP")
oExcel.Close()
Exit Sub
End Try
oExcel.Close()
Dim oDataview As DataView = oDataSet.Tables("conteudo").DefaultView
Dim lTotal As Long = 0
Dim lErro As Long = 0
Dim oLinha As DataRow
Dim iTamanhoCaixa As Integer = 1024
Dim sComCopia As String
For Each oLinha In oDataSet.Tables("conteudo").Rows
If Not (Trim(oLinha("conta").ToString) = "") Then
Console.Write("Criando [" & Trim(oLinha("conta").ToString) & "]...")
sRetorno = ""
sComCopia = Trim(oLinha("enviar_copia").ToString)
iTamanhoCaixa = oLinha("tamanho_mb")
sRetorno = CriaContaPOP(Trim(oLinha("conta").ToString), Trim(oLinha("apelidos").ToString), Trim(oLinha("password").ToString), iTamanhoCaixa, oLinha("nome").ToString, sComCopia, "admin", "password")
'sRetorno = oPainelWS.CriaContaPOP(oLinha("conta"), Trim(oLinha("apelidos").ToString), oLinha("senha"), iTamanhoCaixa, "", sComCopia, "", "")
Console.WriteLine("Retorno: " & sRetorno)
'If Not (sRetorno = "OK") Then
'Exit Sub
'End If
Threading.Thread.Sleep(100)
End If
Next
End Sub
Public Function CriaContaPOP(ByVal sConta As String, ByVal sApelidos As String, ByVal sSenha As String, ByVal iTamanhoCaixaKB As String, ByVal sNome As String, ByVal sForwardTo As String, ByVal sAdminUsuario As String, ByVal sAdminSenha As String) As String
If Not (iTamanhoCaixaKB > 1) Then
Return "ERRO: Tamanho da caixa postal não pode ser inferior a 1 KB"
End If
Dim aContaNome As String() = Split(sConta, "#")
Dim sContaNome As String = ""
Dim sDominio As String = ""
sContaNome = aContaNome(0)
sDominio = aContaNome(1)
Dim oUsuarios As New svcUserAdmin
Dim oUsuarioInfo As New SettingsRequestResult
Dim oResultado As New GenericResult
oResultado = oUsuarios.AddUser2(sAdminUsuario, sAdminSenha, sContaNome, sSenha, sDominio, sNome, "", False, iTamanhoCaixaKB)
If (oResultado.Result = False) Then
Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
End If
If Not (sForwardTo.ToString = "") Then
Dim arrInfo(0) As String
arrInfo(0) = "forwardaddress=" & sForwardTo.ToString
oResultado = oUsuarios.SetRequestedUserSettings(sAdminUsuario, sAdminSenha, sConta, arrInfo)
If (oResultado.Result = False) Then
Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
End If
End If
Return "OK"
End Function
What have you tried? Because as it stands it sounds like all you need to do is
Module Module1
Sub Main()
fnc_CriaContas_Email_Lote()
End Sub
Sub fnc_CriaContas_Email_Lote()
' Do something.
End Sub
End Module
If "fnc_CriaContas_Email_Lote" is a class then you might have to do something like:
Module Module1
Sub Main()
dim email as new cria_contas_lote()
email.fnc_CriaContas_Email_Lote()
End Sub
End Module
Without seeing the cria_contas_lote file its hard to know.
Edit: Below is how you can call it all from just the module
Imports System.Data.OleDb
Module Module1
Sub Main()
fnc_CriaContas_Email_Lote()
End Sub
Sub fnc_CriaContas_Email_Lote()
Dim oPainelWS As PainelControle.svcSmarterMail
Dim sRetorno As String = ""
Try
'oPainelWS = New PainelControle.svcSmarterMail("xxx.xxx.xxx.xxx")
Catch ex As Exception
Console.WriteLine("Erro ao efetuar a conexão no servidor remoto: " & ex.Message)
Exit Sub
End Try
Dim sNomeArquivo As String = "C:\dir\emails.xlsx"
Dim sSQL As String = ""
Dim stringExcel As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & sNomeArquivo & ";Extended Properties=Excel 12.0"
Dim oExcel As New OleDbConnection(stringExcel)
Try
oExcel.Open()
Catch ex As Exception
Console.Write("O arquivo não foi localizado ou ocorreu um erro de abertura no servidor. Arquivo: " & sNomeArquivo)
Console.Write(vbCrLf & "================================================")
Console.Write(vbCrLf & ex.Message)
Console.Write(vbCrLf & "================================================")
Exit Sub
End Try
Dim oDataSet As New DataSet
Try
Dim oExcelAdapter As New OleDbDataAdapter("select * from [contas_pop$]", oExcel)
oExcelAdapter.Fill(oDataSet, "conteudo")
Catch ex As Exception
Console.Write("A tabela CONTAS_POP não foi localizada. Renomeie sua WorkSheet para CONTAS_POP")
oExcel.Close()
Exit Sub
End Try
oExcel.Close()
Dim oDataview As DataView = oDataSet.Tables("conteudo").DefaultView
Dim lTotal As Long = 0
Dim lErro As Long = 0
Dim oLinha As DataRow
Dim iTamanhoCaixa As Integer = 1024
Dim sComCopia As String
For Each oLinha In oDataSet.Tables("conteudo").Rows
If Not (Trim(oLinha("conta").ToString) = "") Then
Console.Write("Criando [" & Trim(oLinha("conta").ToString) & "]...")
sRetorno = ""
sComCopia = Trim(oLinha("enviar_copia").ToString)
iTamanhoCaixa = oLinha("tamanho_mb")
sRetorno = CriaContaPOP(Trim(oLinha("conta").ToString), Trim(oLinha("apelidos").ToString), Trim(oLinha("password").ToString), iTamanhoCaixa, oLinha("nome").ToString, sComCopia, "admin", "password")
'sRetorno = oPainelWS.CriaContaPOP(oLinha("conta"), Trim(oLinha("apelidos").ToString), oLinha("senha"), iTamanhoCaixa, "", sComCopia, "", "")
Console.WriteLine("Retorno: " & sRetorno)
'If Not (sRetorno = "OK") Then
'Exit Sub
'End If
Threading.Thread.Sleep(100)
End If
Next
End Sub
Public Function CriaContaPOP(ByVal sConta As String, ByVal sApelidos As String, ByVal sSenha As String, ByVal iTamanhoCaixaKB As String, ByVal sNome As String, ByVal sForwardTo As String, ByVal sAdminUsuario As String, ByVal sAdminSenha As String) As String
If Not (iTamanhoCaixaKB > 1) Then
Return "ERRO: Tamanho da caixa postal não pode ser inferior a 1 KB"
End If
Dim aContaNome As String() = Split(sConta, "#")
Dim sContaNome As String = ""
Dim sDominio As String = ""
sContaNome = aContaNome(0)
sDominio = aContaNome(1)
Dim oUsuarios As New svcUserAdmin
Dim oUsuarioInfo As New SettingsRequestResult
Dim oResultado As New GenericResult
oResultado = oUsuarios.AddUser2(sAdminUsuario, sAdminSenha, sContaNome, sSenha, sDominio, sNome, "", False, iTamanhoCaixaKB)
If (oResultado.Result = False) Then
Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
End If
If Not (sForwardTo.ToString = "") Then
Dim arrInfo(0) As String
arrInfo(0) = "forwardaddress=" & sForwardTo.ToString
oResultado = oUsuarios.SetRequestedUserSettings(sAdminUsuario, sAdminSenha, sConta, arrInfo)
If (oResultado.Result = False) Then
Return "ERRO: Não foi possivel incluir a conta de e-mail: " & oResultado.Message
End If
End If
Return "OK"
End Function
End Module
Your issue is your missing the following types:
PainelControle.svcSmarterMail
svcUserAdmin
SettingsRequestResult
GenericResult
These are not built in .Net types and must be defined in either another file. Once you've found the missing classes just add them into the project and you should be good to go.
I think you want to make Sub Main run ENTIRE function, and DON'T EXIT as sub main is executed.
I have written answer of your question here : VB.net program with no UI
Sub Main()
'Write whatever you want, and add this code at the END:
Application.Run
End Sub