Does anybody have VB code to emulate Streamwriter for Windows Store?
I know it's been replaced by StorageFolder class but there is no VB sample in MSDN and I can't seem to translate properly from c# examples. Any help would be appreciated. I am just trying to write text (CSV) to a file and save it to the documents folder. In the code below windows store want a stream instead of strPath when I try dim-ing a streamwriter. (been playing with pickerdialog too, but that might be the next hurdle).
Dim strpath As String = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary & "\" & strFileName
'Build String for file*******************
Dim swExport As StreamWriter = New StreamWriter(strpath)
swExport.Flush()
For x = 0 To intCount - 1
strLine = "WriteSomeText"
swExport.WriteLine(strLine)
Next x
Possibly the simplest approach would be to use a MemoryStream if you like StreamWriter, so something like:
Dim sessionData As New MemoryStream()
' TODO: stage data in sessionData
Dim swExport As StreamWriter = New StreamWriter(sessionData)
swExport.Flush()
For x = 0 To intCount - 1
strLine = "WriteSomeText"
swExport.WriteLine(strLine)
Next x
Dim file As StorageFile = await ApplicationData.Current.RoamingFolder.CreateFileAsync("towns.json", CreationCollisionOption.ReplaceExisting)
Using (fileStream As Stream = await file.OpenStreamForWriteAsync())
sessionData.Seek(0, SeekOrigin.Begin)
await sessionData.CopyToAsync(fileStream)
await fileStream.FlushAsync()
End Using
I was making it too difficult. To write to a file I just needed to use storagefolder and storagefile. I have also included the FileSavePicker in the code (note that filetypechoices is mandatory)
Private Async Function btnExport_Click(sender As Object, e As RoutedEventArgs) As Task
'Calls Filepicker to determine location
'Calls Sqlite to select ALL
'Creates CSV file to be saved at location chosen
'save to file
Dim intCount As Integer = "5"
Dim x As Integer
Dim strLine As String 'hold each line for export file
'Create FileName based on date
Dim strDate As String = Date.Today.ToString("MMddyyyy")
Dim strFileName As String = "Export" & strDate & ".csv"
' Configure save file dialog box
Dim dlgPicker As New Windows.Storage.Pickers.FileSavePicker
'add types for picker (manditory field)
Dim types = New List(Of String)
types.Add(".csv")
types.Add(".txt")
'set picker parameters
dlgPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Downloads
dlgPicker.SuggestedFileName = strFileName '"Document" '
dlgPicker.FileTypeChoices.Add("CSV/TXT", types) 'manditory
dlgPicker.DefaultFileExtension = ".csv" 'Filter files by extension
dlgPicker.CommitButtonText = "Save"
' Show save file dialog box
Dim SaveCSV = Await dlgPicker.PickSaveFileAsync()
'************************get data************
Dim sbExport As Text.StringBuilder = New Text.StringBuilder
sbExport.AppendLine(strHeader)
For x = 0 To intCount - 1
strLine = "Get the text you want to write here"
sbExport.AppendLine(strLine)
Next x
'************************************
'write data to file
Await FileIO.WriteTextAsync(SaveCSV, sbExport.ToString)
Dim mb As MessageDialog = New MessageDialog("Done")
Await mb.ShowAsync()
End Function
Related
In my program, I get a series of information instantly from several Internet addresses on a one-to-one basis, but this is delay time and this delay may be part of the momentary information loss . I want to get all the information from all URLs at the same time. Is it possible?
This is part of my program:
For i As Integer = 0 To 1000
Dim wreq As System.Net.HttpWebRequest =
System.Net.WebRequest.Create("http://www........." + slink(i))
wreq.AutomaticDecompression = Net.DecompressionMethods.GZip
Dim wres As System.Net.WebResponse = wreq.GetResponse
Dim s As System.IO.Stream = wres.GetResponseStream
Dim sr As New System.IO.StreamReader(s)
Dim html As String = sr.ReadToEnd
Dim sOutput As String = html
Dim file As System.IO.StreamWriter
Dim masir As String = TextBox1.Text & "tm\Archive\" + slink(i).ToString
file = My.Computer.FileSystem.OpenTextFileWriter(masir, True)
file.Write(html)
file.Close()
Next
I am using the following vb code to get the list of files in a ftp directory and populate a database table with it to be used in another integration process. Please forgive my bad bad programming skills (I am not a vb.net developer).
Public Sub Main()
Dim StrFolderArrary As String() = Nothing
Dim StrFileArray As String() = Nothing
Dim fileName As String
Dim RemotePath As String
RemotePath = Dts.Variables("User::FTPFullPath").Value.ToString()
Dim ADODBConnection As SqlClient.SqlConnection
ADODBConnection = DirectCast(Dts.Connections("DB_Connection").AcquireConnection(Dts.Transaction), SqlClient.SqlConnection)
Dim cm As ConnectionManager = Dts.Connections("FTP_Connection") 'FTP connection manager name
Dim ftp As FtpClientConnection = New FtpClientConnection(cm.AcquireConnection(Nothing))
ftp.Connect() 'Connecting to FTP Server
ftp.SetWorkingDirectory(RemotePath) 'Provide the Directory on which you are working on FTP Server
ftp.GetListing(StrFolderArrary, StrFileArray) 'Get all the files and Folders List
'If there is no file in the folder, strFile Arry will contain nothing, so close the connection.
If StrFileArray Is Nothing Then
ftp.Close()
'If Files are there, Loop through the StrFileArray arrary and insert into table
Else
For Each fileName In StrFileArray
'MessageBox.Show(fileName)
Dim SQLCommandText As String
SQLCommandText = "INSERT INTO dbo._FTPFileList ([DirName],[FileName]) VALUES (N'" + RemotePath + "', N'" + fileName + "')"
'MessageBox.Show(SQLCommandText)
Dim cmdDatabase As SqlCommand = New SqlCommand(SQLCommandText, ADODBConnection)
cmdDatabase.ExecuteNonQuery()
Next
ftp.Close()
End If
' Add your code here
'
Dts.TaskResult = ScriptResults.Success
End Sub
It works fine and I get the results in the database table. The problem is that the encoding of the strings coming from FTP makes the file names with accentuation to be written incorrectly as shown in the example below.
database table
The correct file name is Razão and I know that the db collation is correct since it can be written like this.
So I tried to convert the strings using this code for each file name in the string array but without any success.
For Each fileName In StrFileArray
Dim utf8 As UTF8Encoding = New UTF8Encoding(True, True)
Dim bytes As Byte() = New Byte(utf8.GetByteCount(fileName) + utf8.GetPreamble().Length - 1) {}
Array.Copy(utf8.GetPreamble(), bytes, utf8.GetPreamble().Length)
utf8.GetBytes(fileName, 0, fileName.Length, bytes, utf8.GetPreamble().Length)
Dim fileName2 As String = utf8.GetString(bytes, 0, bytes.Length)
I believe it is coming with different encoding from the FTP side so I would like to know how to convert the strings during the GetListing method.
Or do you have any ideas how to deal with this?
Thanks in advance.
edit:
I also tried the following code without success.
Dim utf8 As Encoding = Encoding.UTF8
Dim w1252 As Encoding = Encoding.GetEncoding(1252)
Dim w1252Bytes As Byte() = w1252.GetBytes(fileName)
Dim utf8Bytes As Byte() = Encoding.Convert(w1252, utf8, w1252Bytes)
Dim utf8Chars As Char() = New Char(utf8.GetCharCount(utf8Bytes, 0, utf8Bytes.Length) - 1) {}
utf8.GetChars(utf8Bytes, 0, utf8Bytes.Length, utf8Chars, 0)
Dim fileName2 As String = New String(utf8Chars)
i just want to ask how can i add a password on a existing PDF file, i just created a pdf file using crystal reports and i kinda need to add some security features for the report. Thank you very much in advance.
lets say the file "c:\Folder1\sample.pdf" already exist. i have seen codes like the one below, but i don't know if it works because i don't know what to add in my reference to make it work
' Define input and output files path.
Dim intputFilePath As String = Program.RootPath + "\\" + "1.pdf"
Dim outputFilePath As String = Program.RootPath + "\\" + "1_with_pw.pdf"
' Set passwords for user and owner.
Dim userPassword As String = "you"
Dim ownerPassword As String = "me"
' Create password setting.
Dim setting As PasswordSetting = New PasswordSetting(userPassword, ownerPassword)
' Add password to plain PDF file and output a new file.
Dim errorCode As Integer = PDFDocument.AddPassword(intputFilePath, outputFilePath, setting)
If errorCode = 0 Then
Console.WriteLine("Success")
Else
Console.WriteLine("Failed")
End If
Dim WorkingFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim InputFile As String = Path.Combine(WorkingFolder, "PSNOs.pdf")
Dim OutputFile As String = Path.Combine(WorkingFolder, "PSNOs_enc.pdf")
Using input As Stream = New FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read)
Using output As Stream = New FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None)
Dim reader As New PdfReader(input)
PdfEncryptor.Encrypt(reader, output, True, Nothing, "secret", PdfWriter.ALLOW_SCREENREADERS)
End Using
End Using
the word "PdfReader" have an error message but it doesn't ask to import something..
I am trying to add drag and drop functionality to my form so that I can drag an attachment from an email and it will save the attachment.
I get an error saying Required Privileges not held by client. I want to get around this.
Here is my code:
If e.Data.GetDataPresent("FileGroupDescriptor") Then
Dim theStream As Stream = DirectCast(e.Data.GetData("FileGroupDescriptor"), Stream)
Dim fileGroupDescriptor As Byte() = New Byte(511) {}
theStream.Read(fileGroupDescriptor, 0, 512)
Dim fileName As New StringBuilder("")
Dim i As Integer = 76
While fileGroupDescriptor(i) <> 0
fileName.Append(Convert.ToChar(fileGroupDescriptor(i)))
i += 1
End While
theStream.Close()
Dim theFile As String = "c:\" + fileName.ToString() 'change the c:\ to any path you want
Dim ms As MemoryStream = DirectCast(e.Data.GetData("FileContents", True), MemoryStream)
Dim fileBytes As Byte() = New Byte(ms.Length - 1) {}
ms.Position = 0
ms.Read(fileBytes, 0, CInt(ms.Length))
Dim fs As New FileStream(theFile, FileMode.OpenOrCreate)
fs.Write(fileBytes, 0, CInt(fileBytes.Length))
fs.Close()
End If
You most certainly do not have permissions to write to c:\.
I suggest writing to your desktop or somewhere using the My.Computer.FileSystem.SpecialDirectories object:-
Dim theFile As String = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Desktop, filename.ToString)
Check this article out for all the options available to you: https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.specialdirectories.aspx
I am trying to make a program that writes the binary code of a file in a separate text file.
When I use this program on a text file, it doesn't write anything in the new file. I then tested this for .jpg and .mp3 files and the program seems to write most of the binary code but leaves out the last couple of bytes. Here is my code:
Sub Main()
Console.Write("Filename: ")
Dim Filename As String = Console.ReadLine()
Console.Write("Extension: ")
Dim Extension As String = Console.ReadLine()
Console.WriteLine()
Dim Stream_1 As FileStream = New FileStream(Filename & "." & Extension, FileMode.Open)
Dim Stream_2 As FileStream = New FileStream(Filename & "_b.txt", FileMode.Create)
Dim Reader_1 As BinaryReader = New BinaryReader(Stream_1)
Dim Writer_2 As StreamWriter = New StreamWriter(Stream_2)
Dim File_Bytes() As Byte = Reader_1.ReadBytes(Convert.ToInt32(Stream_1.Length))
Dim Binary_String As String = ""
'These are used to a add line break after every 8 bytes
Dim Binary_String_Collection As String = ""
Dim Counter As Integer
For Each File_Byte In File_Bytes
Counter += 1
Binary_String = Convert.ToString(File_Byte, 2)
For I = 1 To 8 - Binary_String.Length
Binary_String = "0" & Binary_String
Next
Binary_String_Collection = Binary_String_Collection & Binary_String & " "
If Counter = 8 Then
Writer_2.WriteLine(Binary_String_Collection)
Counter = 0
Binary_String_Collection = ""
End If
Next
If Binary_String_Collection <> "" Then
Writer_2.WriteLine(Binary_String_Collection)
End If
Console.ReadLine()
End Sub
At first I thought that my program wasn't reading the binary code properly so I added console outputs at locations where it writes to the file. The program displayed correct output so I'm confused why it isn't writing properly.
Make sure you close the file and Dispose of the streams correctly.