Renaming files when saving to location - vb.net

I am using the below code to copy a file to a network location and store the file information in an access database.
Dim SqlString1 As String = "INSERT INTO document (incidentid, documentno, documentname, documentpath) VALUES (#incid, #docid, #FileName, #FilePath)"
Using conn As New OleDbConnection(ConnString)
conn.Open()
If Me.TextBox1.Text <> "" Then
'THIS WILL SAVE THE FILE TO A LOCATION
Dim fileLocation As String = OpenFileDialog1.FileName
File.Copy(fileLocation, Path.Combine("\\10.1.10.5\NonConformance\Document\", Path.GetFileName(fileLocation)), True)
'THIS WILL SAVE A FILE PATH TO THE ACCESS DB
Using cmd As New OleDbCommand(SqlString1, conn)
'cmd.CommandType = CommandType.Text
cmd.Parameters.AddWithValue("#incid", doc1.Text)
cmd.Parameters.AddWithValue("#docid", doc2.Text)
cmd.Parameters.AddWithValue("#FileName", Path.GetFileName(Me.OpenFileDialog1.FileName))
cmd.Parameters.AddWithValue("#FilePath", "\\10.1.10.5\NonConformance\Document\" & Path.GetFileName(Me.OpenFileDialog1.FileName))
cmd.ExecuteNonQuery()
conn.Close()
End Using
End If
conn.Close()
End Using
I am concerned that if a user uploads a file with the same filename as one already in the folder it will cause issues when trying to retrieve information at a later date.
So can anyone tell me how to rename the file when copying it to the network location. Ideally I would like to rename it to be the #incid_#docid parameters

I ended up changing the
Path.GetFileName(fileLocation))
element to read
Path.GetFileName("INC" & Label6.Text & "DOC" & doc2.Text & ".pdf")
This will solve the issue for me, thanks for the responses.

Related

Mapping onedrive files to string for OLEDB to read specific files within drive Visual Basic .NET

I have a program that reads an excel file that is on my local disk. I need this file to be accessible to other individuals to edit the file and allow the program to execute based on its contents. The way were making this accessible is sharing it via OneDrive. The file is read by a OLEDB Script I wrote that takes the directory of the file to read it and load into temp table on the app. I have been searching online for a solution to this in visual basic but a lot of the solutions are written in c# and its hard for me to translate or understand the logic. Here is an example of the solution in pseudo code:
If (ONEDRIVE_FILE_DIRECTORY IsNot Nothing) Then
' STORE FILE FROM ONE DRIVE INTO LOCAL_FILE_DIRECTORY
End If
Dim strConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="LOCAL_FILE_DIRECTORY";Extended Properties=""Excel 8.0;HDR=YES"";"
Dim dt As New DataTable
dt.TableName = "Results"
dt.Columns.AddRange(New DataColumn() {New DataColumn("LOC_ID", GetType(String)),
New DataColumn("EMAIL", GetType(String)),
New DataColumn("INTERVAL", GetType(String)),
New DataColumn("PASSWORD", GetType(String))
})
Dim connection As OleDbConnection = New OleDbConnection(strConnectionString)
Dim strSQL As String = "SELECT [LOC_ID], [EMAIL], [INTERVAL], [PASSWORD] FROM [Report$] WHERE [LOC_ID] <> ''"
Try
connection.Open()
Using Adp As New OleDbDataAdapter(strSQL, connection)
Adp.Fill(dt)
End Using
Catch ex As Exception
LogMessage(ex.ToString, "Error message in """ & strApplicationName & """ job on " & strComputerName & " by: " & strUsername)
SendEmailErrorMessage(ex.ToString)
Finally
If connection.State = ConnectionState.Open Then
connection.Close()
End If
End Try

How to connect to a Clipper (E5) DBF File (with an SMT) using vb.net

I am trying to connect to a DBF (HISTORY.DBF) that has a linked SMT file (HISTORY.SMT). I have multiple DBF files and I can connect to all of them except the ones with SMT files.
Looking at the header information of the DBFs suggests it is a Clipper (E5 Header) format DBF which reads fine using the connection code below for most files, but once I try to read a file with an associated SMT it fails with the fault:
External table is not in the expected format
My Code is as below
Dim dsDataSet As New DataSet
Dim ConnectionString As String
Dim daDataAdapter As OleDb.OleDbDataAdapter
Dim dBaseConnection As New System.Data.OleDb.OleDbConnection
Dim strFilePath As String = gloStrPath & "data"
Dim strDBF As String = "HISTORY.DBF"
Try
ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFilePath & ";Extended Properties=dBase III;"
dBaseConnection = New System.Data.OleDb.OleDbConnection(ConnectionString)
If dBaseConnection.State = 0 Then dBaseConnection.Open()
Catch ex As Exception
MsgBox(ex.Message, 16, "Error")
End Try
Try
daDataAdapter = New OleDb.OleDbDataAdapter("select * from " & strDBF, dBaseConnection)
daDataAdapter.Fill(dsDataSet, "Name")
Catch ex As Exception
MsgBox(ex.Message, 16, "Error")
End Try
Can anyone offer any insight into what I am doing wrong or what I am missing?
These files appear to be DBFs that were created with the HiPer-Six format with SMT memo files. Check this https://www.dbf2002.com/dbf-file-format.html

Uploading Excel File into MS Access using vb.net

I am trying to import an Excel file into an Access DB via vb.net
the idea is the customer can export the data into excel, modify it, add, delete them importing it back.
The data exported has exactly the same format than the table to import to.
I am using the code below:
Try
Dim strFileName As String = String.Empty
Dim XLda As New OleDbDataAdapter
Dim ExcelTables As New DataTable
Dim StrSelect = "SELECT * FROM [{0}]"
OpenFileDialog1.FileName = ""
OpenFileDialog1.InitialDirectory = mdlGlobalStuff.sMasterDataPath
OpenFileDialog1.Filter = "Excel|*.xls|All files (*.*)|*.*"
If OpenFileDialog1.ShowDialog() <> Windows.Forms.DialogResult.OK Then
Exit Sub
End If
strFileName = OpenFileDialog1.FileName
Dim MyXLConnection As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
Using MyXLConnection
Using cmd As New OleDbCommand
cmd.Connection = MyXLConnection
cmd.CommandText = "INSERT INTO [MS Access;Database=InvoicingToolDB.accdb].[tbl_Bases] SELECT * FROM [Sheet1$]"
If MyXLConnection.State = ConnectionState.Open Then
MyXLConnection.Close()
End If
MyXLConnection.Open()
cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MsgBox("ImportLinkLabel_LinkClicked: Importing Base data" & vbCrLf & ErrorToString())
End Try
I always have an error message saying:
Unrecognized database format 'c:\--path to db--\InvoicingToolDB.accdb'
The path is correct and I don't understand why the format wouldn't be recognized.
Ok I have found the issue. The OLEDB Provider version was not the right one (4.0 is not reading Access .accdb format but old .mdb format only)
Replacing:
Dim MyXLConnection As New OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
With:
Dim MyXLConnection As New leDbConnection("provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & strFileName & ";Extended Properties=Excel 8.0;")
Works perfectly.

Reading Excel in .NET - some columns are read in as null

i am trying to read in some data from an excel:
If (FileUpload1.PostedFile.ContentType = "application/vnd.ms-excel") Then
Dim filename As String = Path.GetFileName(FileUpload1.FileName)
'Session("userid") & "-" & Date.Now()
filepath = "\excel\" & Session("userid") & "_" & Now.Date().ToString("Mdy") & "_" & filename
FileUpload1.SaveAs(Server.MapPath("~/") & filepath)
ReadExcel(filepath)
Else
StatusLabel.Text = "Only Excel file types are accepted"
End If
everything seems to be fine, except when one of the columns sometimes reads in as NULL. seems like that happens if it's of a different type.
i can't figure out what it is. someone help me please....
Sub ReadExcel(ByVal filepath As String)
Dim MyConnection As System.Data.OleDb.OleDbConnection
Dim DtSet As System.Data.DataSet
Dim MyCommand As System.Data.OleDb.OleDbDataAdapter
MyConnection = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='" & Server.MapPath("~/") & filepath & "';Extended Properties=Excel 8.0;")
DtSet = New System.Data.DataSet
Try
MyCommand.Fill(DtSet)
'gwResults.DataSource = DtSet.Tables(0)
LoopSources(DtSet)
'gwResults.DataBind()
MyConnection.Close()
Catch ex As Exception
StatusLabel.Text = "Import Excel status: The file could not be loaded. The following error occured: <br>" + ex.Message
End Try
End Sub
You need to include Extended Properties="Excel 8.0;IMEX=1;" in your connection string. Excel tries to determine the data type of your columns by reading the first few rows. Once it thinks it knows the data type, anything that doesn't conform to that is coerced to NULL. Very annoying. IMEX=1 tells it to read your data as intermixed and should resolve your problem. If you have a header row, you should also consider including HDR=YES. See this link: http://www.connectionstrings.com/excel for more info.
Probably the type of column is determined incorrectly. By default Jet provider reads 8 first rows to determine the type of column. And if these 8 lines contain something wrong you'll get a problem.
This can be changed by setting TypeGuessRows setting in registry.

vb.net traversing an xls / xlsx file?

is there a simple way in vb.net to load an excel file and read it? perhaps there is a way to load the file but have it not be visible to the user?
Alex - here is some old code I dug up to query excel. Pretty basic scenario here. Don't pay attention to the poor error handling and lack of the 'Using' construct.
Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0" & _
";Data Source=" & ExcelFile & _
";Extended Properties=Excel 8.0;"
Dim conn As OleDbConnection = Nothing
Dim dt As System.Data.DataTable = Nothing
Dim excelDataSet As New DataSet()
Try
conn = New OleDbConnection(connString)
conn.Open()
dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)
If dt Is Nothing Then
Return Nothing
End If
Dim excelSheets(dt.Rows.Count) As String
Dim i As Integer = 0
For Each row As DataRow In dt.Rows
excelSheets(i) = row("TABLE_NAME").ToString
System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1)
If i = SheetNumber Then
Exit For
End If
Next
Using excelCommand As New OleDbCommand("Select * from [" & excelSheets(SheetNumber - 1) & "]", conn)
Using excelAdapter As New OleDbDataAdapter(excelCommand)
excelAdapter.Fill(excelDataSet)
End Using
End Using
Catch ex As OleDbException
Throw
Catch ex As Exception
Throw
Finally
conn.Close()
If conn IsNot Nothing Then
conn.Dispose()
End If
If dt IsNot Nothing Then
dt.Dispose()
End If
End Try
Return excelDataSet
Work with the Excel Object Model directly from .NET.
You can use ado.net to read from excel spreadsheets via the OLEDB JET 4 provider
This just opens the excel file as a file stream instead of opening the actual excel spreadsheet.
Alternatively you could use com-interop and simply set the application object visible property to false.
See http://www.connectionstrings.com/excel
One gotcha to watch out for when using .net and com interop with any office application is that if you try opening the application as a user who is more of a windows service than an actual human user then you will need to login to windows as that user and open the relevant application as that user so that all the registry entries are correctly updated for certain features of the office application.
If you have a more simple (ie small) excel spreadsheet that does not need to be dynamic, I think you could export it as a comma delimited file and then use a loop and streamreader object to parse each comma seperated value into an array.
Kinda round about though...