to save xml file in Vb.net - vb.net

Public Function UploadCourseXML(ByVal fileStream As String, companyID As Integer, ByVal tokenID As String) As String Implements ICorePointService.UploadCourseXML
If (Not IsCustomerAuthentication(companyID, tokenID)) Then
Throw New Exception("Authentication failed. Please provider Company ID and Token ID")
End If
Dim doc As XDocument = XDocument.Parse(fileStream)
doc.Save("Update_XML")' error occures here... Access to the path c:\...etc. is denied
.. i want to save this in solution explorer
Return "result"
End Function

Refer this link :
http://support.microsoft.com/kb/301233
This for windows & web also
Imports System.IO
Imports System.Net
Imports System.Xml
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'To just download xml text
'Download text and save
Dim wc As New WebClient
Dim xmlText As String = wc.DownloadString("http://www.localcallingguide.com/xmllocalexch.php?exch=015800")
File.WriteAllText("new file path.xml", xmlText)
'Or
'To load stream directly into XML Document :
'Get data in stream
Dim webRequest As WebRequest = webRequest.Create("http://www.localcallingguide.com/xmllocalexch.php?exch=015800")
Dim webResponse As WebResponse = webRequest.GetResponse
Dim webStream As Stream = webResponse.GetResponseStream
'Optionally
'If you want you can read text from stream
'Dim reader As New StreamReader(webStream)
'reader.ReadToEnd 'will give same output as wc.downloadString()
'Load stream
Dim xmlDoc As New XmlDocument
xmlDoc.Load(webStream)
'select any level nodes using xpath
Dim Nodes As XmlNodeList = xmlDoc.SelectNodes("//lca-data/prefix/exch")
'iterate in selected nodes
For Each node As XmlNode In Nodes
RichTextBox1.AppendText(node.InnerText & vbCrLf)
Next
End Sub
End Class

You'll get a Access to the path '...' is denied error if the folder is flagged ReadOnly. You need to remove this flag prior to saving the file.
Dim info As DirectoryInfo = New DirectoryInfo("C:\folder1\folder2\folder3")
If (info.Exists AndAlso ((info.Attributes And FileAttributes.[ReadOnly]) = FileAttributes.[ReadOnly])) Then
info.Attributes = (info.Attributes Xor FileAttributes.[ReadOnly])
End If
If you're writing to an existing file, also make sure the file is not flagged ReadOnly. Just change DirectoryInfo to FileInfo.
Dim info As FileInfo = New FileInfo("C:\folder1\folder2\folder3\file.ext")

You may refer to the below given link to find out your problem,
http://support.microsoft.com/kb/2623670#method4

Related

Utilizing wildcards and variables for getFiles

I am kinda new to VB.net, so I am not sure if I try this the right way. I have the following piece of code.
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Dim TextLine As String
Do While objReader.Peek() <> -1
Dim newString As String = TextLine.Replace(vbCr, "").Replace(vbLf, "") & ".wav"
Dim SongName As String = My.Computer.FileSystem.GetName(newString)
Dim MyFile As String = Dir("C:\AllSongs\" & newString)
Dim Searchquery As IEnumerable(Of String) = IO.Directory.EnumerateFiles("C:\AllSongs", "*", IO.SearchOption.AllDirectories).Where(Function(f) IO.Path.GetFileNameWithoutExtension(f).IndexOf(SongName, StringComparison.CurrentCultureIgnoreCase) >= 0)
For Each Result In Searchquery
ListBox1.Items.Add(Result)
Next
I am trying to use the lines in the text file, and get the .wav in AllSongs dir that partially correspond in these files. Can it be done?
Edit: Part of the code contains a media player. I want to be able to play songs from this player, by choosing files in the list.
Private Sub ListBox1_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.DoubleClick
AxWindowsMediaPlayer1.URL = ListBox1.SelectedItem
Dim variables As New Dictionary(Of String, String)()
Dim selectedItem As Object = ListBox1.SelectedItem
variables("MyDynamicVariable") = selectedItem ' Set the value of the "variable"
selectedItem1 = selectedItem
Dim value As String = variables("MyDynamicVariable") ' Retrieve the value of the variable
End Sub
Incidental to the question, but important, is that when you're working with files it's often necessary to clean up some resources (file handles, I guess) that the operating system uses even though you don't see it directly in the code as written. There is a way of doing that automatically with the Using statement, as shown in the following code.
To find out if a filename contains some text (string), you can extract the filename with no path or extension with Path.GetFileNameWithoutExtension and check if it contains the desired string with the IndexOf function, which lets you ignore uppercase/lowercase by specifying how to do the check.
I notice from an update to the question that some improvements can be made, such as using a Class for the song entries so that the displayed list can have more information behind it, which means that the song name can be shown on its own but you can get the full path to the file when you click on it.
I made a new Windows Forms project and added just a ListBox to it, and used this code to show the full path (which you can use for your media player) to the song when its name is double-clicked:
Imports System.IO
Public Class Form1
Public Class SongEntry
Property Name As String
Property FullName As String
End Class
Sub PopulateSongList(musicDirectory As String, songsList As String)
Dim songList As New List(Of SongEntry)
Using sr As New System.IO.StreamReader(songsList)
Do While Not sr.EndOfStream
Dim thisSong = sr.ReadLine()
If thisSong <> "NaN" Then
Dim fs = Directory.EnumerateFiles(musicDirectory, "*.wav", SearchOption.AllDirectories).
Where(Function(f) Path.GetFileNameWithoutExtension(f).IndexOf(thisSong, StringComparison.CurrentCultureIgnoreCase) >= 0).
Select(Function(g) New SongEntry With {.Name = Path.GetFileNameWithoutExtension(g), .FullName = g})
songList.AddRange(fs)
End If
Loop
End Using
ListBox1.DataSource = songList
ListBox1.DisplayMember = "Name"
ListBox1.ValueMember = "FullName"
End Sub
Private Sub ListBox1_DoubleClick(sender As Object, e As EventArgs) Handles ListBox1.DoubleClick
Dim lb = DirectCast(sender, ListBox)
If lb.SelectedIndex >= 0 Then
Dim fullPathToSong = lb.SelectedValue.ToString()
MsgBox(fullPathToSong)
End If
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim songsList = "C:\temp\AllSongs\songsList.txt"
Dim musicDirectory = "C:\temp\AllSongs"
PopulateSongList(musicDirectory, songsList)
End Sub
End Class

vb.net XmlDocument.SelectSingleNode and xmlNamespace issue

I am trying to get this code working but somehow is not getting the content
My Code
Dim m_xmld As XmlDocument
Dim m_nodelist As XmlNodeList
Dim m_node As XmlNode
'Create the XML Document
m_xmld = New XmlDocument()
'Load the Xml file
m_xmld.Load("http://feeds.thescore.com/nfl.rss")
'Get the list of name nodes
m_nodelist = m_xmld.SelectNodes("/rss/channel/item")
Dim content As XmlNamespaceManager = New XmlNamespaceManager(m_xmld.NameTable)
content.AddNamespace("content", "http://schemas.xmlsoap.org/soap/envelope/")
'Loop through the nodes
For Each m_node In m_nodelist
If Not m_node.SelectSingleNode("content:encoded",content) Is Nothing AndAlso Len(m_node.SelectSingleNode("content:encoded",content).InnerText) > 0 Then
response.Write(m_node.SelectSingleNode("content:encoded",content))
response.Flush()
end if
Next
Can someone help me please?
I did it this way and could see all of the content nodes, that appear to be html.
Imports <xmlns:atom="http://www.w3.org/2005/Atom">
Imports <xmlns:content="http://purl.org/rss/1.0/modules/content/">
Imports <xmlns:dc="http://purl.org/dc/elements/1.1/">
Imports <xmlns:georss="http://www.georss.org/georss">
Imports <xmlns:media="http://search.yahoo.com/mrss/">
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim xe As XElement = XElement.Load("http://feeds.thescore.com/nfl.rss")
Dim ie As IEnumerable(Of XElement) = xe...<content:encoded>
For Each c As XElement In ie
Debug.WriteLine(c.Value)
Next
End Sub
End Class
I managed with different approach I import first the data with webClient replaced the with and worked like a charm

Visual Basic - Web Request 403 Forbidden

I am new to Visual Basic so I dont know much about Syntax e.t.c
So if anyone could help me out that be great!
Im getting a 403 Forbidden Error most likely because of the User Agent being used. The website is probably picking up that its not an actual user entering the Website and therefore blocks access.
How do I apply a User Agent that will bypass this issue? I have no idea where to put the Syntax.
My Code:
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim sources(1) As String
array(0) = "http://proxy-ip-list.com"
array(1) = "http://sslproxies24.blogspot.com/feeds/posts/default"
For Each element As String In sources
'Connect to the Proxy Source;
Dim source As Net.HttpWebRequest = Net.WebRequest.Create(element)
'Prepare the Response;
Dim response As Net.HttpWebResponse = source.GetResponse
'Load the HTML;
Dim reader As IO.StreamReader = New IO.StreamReader(response.GetResponseStream())
Dim html As String = reader.ReadToEnd
'Regex;
Dim expression As New Regex("[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}:[0-9]{1,4}")
'Set the Matches variable to the Matched Sections of the HTML source;
Dim matches As MatchCollection = expression.Matches(html)
'Add the proxies to the ListBox;
For Each proxy As Match In matches
ListBox1.Items.Add(proxy)
Next
Next
End Sub
End Class

Load PDF to MemoryStream in VB.NET

I'm using this code to read my XFA data to my vb.net application. However, I cannot figure out how to load the populatedPDFFrom to the application.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim filePath As String
filePath = "d:\waiver_testing\test_pdf\rfrprg67.pdf"
TextBox1.Text = Export(filePath)
End Sub
Public Shared Function Export(populatedPDFForm As System.IO.Stream) As System.IO.MemoryStream
' Exports XFA data from a PDF File
' <param name="populatedPDFForm">a readable stream of the PDF with a populated form</param>
' <returns>A stream containing the exported XML form data</returns>
Dim outputStream As New System.IO.MemoryStream()
Dim reader As New iTextSharp.text.pdf.PdfReader(populatedPDFForm)
Dim settings As XmlWriterSettings = New XmlWriterSettings
settings.Indent = True
'settings.OmitXmlDeclaration = True
Using writer = XmlWriter.Create(outputStream, settings)
reader.AcroFields.Xfa.DatasetsNode.WriteTo(writer)
End Using
Return outputStream
End Function
Error on line:
textbox1.text = Export(filePath)
Error:
Value type "String" cannot be converted to to "System.IO.Stream"
Can someone please throw me a bone?
Well, you can not assign a MemoryStream to a string. You need to convert it first. For example to read the stream as Ascii you can use Encoding.ASCII.GetString.
Also, your Export function seems to take in a stream as a parameter and not a file path. To handle that write:
Using inStream As Stream = File.OpenRead(filePath)
TextBox1.Text = Encoding.ASCII.GetString(Export(inStream).ToArray())
End Using

vb.net can read\ open or save file because of file name issue

I’m trying to edit my code to open all files in the folder ATC (including any subdirectory’s)
If any of these files are found not to contain the text “Index…” that, that particular file is appended to include the text found in document “C:\stuff.txt” and then save the file with the changes…
The issues I'm having are with file names.
First problem is that my TARGET_FILE won’t open; second issue is that my TARGET_FILE wont save?
Can anybody help? I have marked the code with '<<----ISSUE #1 & '<<----ISSUE #2 too point out the problems.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'Get folder containing files to ellipherate through...
Dim TARGET_FILE() As String = IO.Directory.GetFiles("C:\VTS\TREADSTONE LT\ATC", "*", SearchOption.AllDirectories)
For Each file As String In TARGET_FILE
Dim sReader As New StreamReader(file)
Dim content As String = sReader.ReadToEnd()
sReader.Close()
If Text.Contains("Index...") Then
'do nothing
Else
Dim text As String = IO.File.ReadAllText(TARGET_FILE) '<<----ISSUE #1
Dim EXTRA As String = IO.File.ReadAllText("C:\STUFF.TXT")
Dim index As Integer = text.IndexOf("<Tools>")
Dim countChars As Integer
countChars = "<Tools>".Length
If index >= 0 Then
' String is in file, starting at character "<Tools>" insert text "TEST_HELLO"
text = text.Insert(index + countChars, EXTRA)
Dim Writer As System.IO.StreamWriter
Writer = New System.IO.StreamWriter(TARGET_FILE) '<<----ISSUE #2
Writer.Write(text)
Writer.Close()
'Close this program\ form...
'Me.Close()
End If
End If
Next
Me.Close()
End Sub
Dim TARGET_FILE() As String 'This represent an array of string
File.ReadAllText
and
System.IO.StreamWriter
does not receive an array of string as parameter
You should iterate your TARGETFILE array collection and do ReadAllText for every file:
For Each File As String In TARGETFILE
Dim ReadedText as string = System.IO.File.ReadAllText(File)
Dim writer As New System.IO.StreamWriter("DestinationPath")
writer.Write(ReadedText )
Write.Close()
Next