I'm currently working on an application that can export a DataGridView to CSV file and upload it to OneDrive if you press a button. At the moment, the file is successfully being exported as a CSV file and I can upload it to OneDrive but unfortunately when I click into it, it is blank. I'm not sure what I'm doing wrong because the file appears in the OneDrive folder and when I check the file with Process.Start(fName.Text & ".txt"), the data is all there.
This is my code:
Dim newFile As System.IO.FileStream
newFile = System.IO.File.Create("C:\Users\User_Name\OneDrive\Low Stock Notifier\" & fName.Text & ".txt") 'If changed to desktop, data is present
Dim headers = (From header As DataGridViewColumn In LStock_Viewer.Columns.Cast(Of DataGridViewColumn)()
Select header.HeaderText).ToArray
Dim rows = From row As DataGridViewRow In LStock_Viewer.Rows.Cast(Of DataGridViewRow)()
Where Not row.IsNewRow
Select Array.ConvertAll(row.Cells.Cast(Of DataGridViewCell).ToArray, Function(c) If(c.Value IsNot Nothing, c.Value.ToString, ""))
Using Writer As New IO.StreamWriter(fName.Text & ".txt")
Writer.WriteLine(String.Join(",", headers))
For Each r In rows
Writer.WriteLine(String.Join(",", r))
Next
End Using
Process.Start(fName.Text & ".txt") 'when file opens here, data is present but even when I manually save it, the file is still blank in onedrive
I've tried using the code from How to upload files to MS one drive using vb.net? but (maybe because I'm not familiar with functions) can't get it to work with a button.
Thanks!
CodePudding user response:
This creates a file in your OneDrive folder:
Dim newFile As System.IO.FileStream
newFile = System.IO.File.Create("C:\Users\User_Name\OneDrive\Low Stock Notifier\" & fName.Text & ".txt")
but you never actually use that file, or close it for that matter. When it's time to save the data, you do this:
Using Writer As New IO.StreamWriter(fName.Text & ".txt")
which creates a different file in your project folder. It is that file that you open here:
Process.Start(fName.Text & ".txt")
If you expect the data to be in a file in your OneDrive folder then that's where you should save the data.
Dim filePath = IO.Path.Combine("C:\Users\User_Name\OneDrive\Low Stock Notifier", fName.Text & ".txt")
'...
Using Writer As New IO.StreamWriter(filePath)
'...
End Using
Process.Start(filePath)
let this be a lesson that, if you want to use a value multiple times, assign it to a variable and then use that variable multiple times. Don't keep using expressions to generate the same value because, at best, it's inefficient and, at worst, you'll stuff it up and not actually use the same value.