Hey guys I'm trying to write to an existing file. here is my code:
Dim writeFile1 As StreamWriter = File.OpenWrite("H:\Visual Basic\LoginFixed\Accounts\" + frmLogin.txtUser.Text)
It's saying that Error "Value of type 'System.IO.FileStream' cannot be converted to 'System.IO.StreamWriter'. "
The exception indicates that the File.OpenWrite() method returns a FileStream object.
Dim writeFile1 As FileStream = File.OpenWrite("H:\Visual
Basic\LoginFixed\Accounts\" + frmLogin.txtUser.Text)
See the MSDN on File.OpenWrite() for more information.
Related
I am trying to copy the contents of an embedded file to a string in Visual Basic using Visual Studio 2013. I already have the resource (Settings.xml) imported and set as an embedded resource. Here is what I have:
Function GetFileContents(ByVal FileName As String) As String
Dim this As [Assembly]
Dim fileStream As IO.Stream
Dim streamReader As IO.StreamReader
Dim strContents As String
this = System.Reflection.Assembly.GetExecutingAssembly
fileStream = this.GetManifestResourceStream(FileName)
streamReader = New IO.StreamReader(fileStream)
strContents = streamReader.ReadToEnd
streamReader.Close()
Return strContents
End Function
When I try to save the contents to a string by using:
Dim contents As String = GetFileContents("Settings.xml")
I get the following error:
An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll
Additional information: Value cannot be null.
Which occurs at line:
streamReader = New IO.StreamReader(fileStream)
Nothing else I've read has been very helpful, hoping someone here can tell me why I'm getting this. I'm not very good with embedded resources in vb.net.
First check fileStream that its not empty as it seems its contains nothing that's why you are getting a Null exception.
Instead of writing to file test it by using a msgBox to see it its not null.
fileStream is Nothing because no resources were specified during compilation, or because the resource is not visible to GetFileContents.
After fighting the thing for hours, I discovered I wasn't importing the resource correctly. I had to go to Project -> Properties -> Resources and add the resource from existing file there, rather than importing the file from the Solution Explorer. After adding the file correctly, I was able to write the contents to a string by simply using:
Dim myString As String = (My.Resources.Settings)
Ugh, it's always such a simple solution, not sure why I didn't try that first. Hopefully this helps someone else because I saw nothing about this anywhere else I looked.
I have a problem deleting an XML file after loading it into .XMLDocument.
My code parses the XML file for specific nodes and allocates their values to variables.
Once complete the code processes data based on the values from the XML file.
This works fine until the end when i try to delete the XML file as it is still open and i then get a error "The process cannot access the file because it is being used by another process" which i guess is the XMLDocument reader.
Here is a section of the the XML processing code - this works fine.
`Dim xmlDoc As XmlDocument = New XmlDocument()
xmlDoc.Load(strFileName)
intPassed = xmlDoc.SelectSingleNode("//CalibrationPassed").InnerText
boolCheck = xmlDoc.SelectSingleNode("//ChecksComplete").InnerText
intCertRequired = xmlDoc.SelectSingleNode("//Schedule").InnerText
Console.WriteLine("Calibration Passed: " & intPassed)
Console.WriteLine("Checks Complete:" & boolCheck)
Console.WriteLine("Schedule: " & intCertRequired)
strFirstName = xmlDoc.SelectSingleNode("//FirstName").InnerText
strEMail = xmlDoc.SelectSingleNode("//Email").InnerText
strCusEmail = xmlDoc.SelectSingleNode("//CustomerEmail").InnerText
strCompanyName = xmlDoc.SelectSingleNode("//CompanyName").InnerText
strContractNumber = xmlDoc.SelectSingleNode("//ContractNo").InnerText
Console.WriteLine("First name: " & strFirstName)
Console.WriteLine("Email: " & strEMail)
Console.WriteLine("Customer EMail: " & strCusEmail)
Console.WriteLine("Company name: " & strCompanyName)
Console.WriteLine("Contract no: " & strContractNumber)
Console.WriteLine("XML Parsing Complete")
`
The code being used to delete the file is:
If System.IO.File.Exists(strFileName) = True Then
System.IO.File.Delete(strFileName)
Console.WriteLine("Deleted XML file")
End If
Any help on where I'm going wrong would be great-fully received.
Thanks
XmlDocument.Load uses a stream reader under the hood. There are two strategies for avoiding this:
1) A Using block will close/dispose your stream automatically and promptly
Using xmlDoc As XmlDocument = New XmlDocument()
xmlDoc.Load(strFileName)
'all of your copying stuff
End Using
'now delete your file
2) Load your XML and avoid using a reader:
Dim strXml as string
strXml = System.IO.File.ReadAllText(strFileName)
Dim xmlDoc As XmlDocument = New XmlDocument()
xmlDoc.LoadXml(strXml)
'and then the rest of your code
The downside to the 2nd approach is that my example doesn't consider any other encoding, but it should get you past your current problem. Dealing with various encoding options is a whole different matter.
If you're not using an xmlreader, then try this:
Dim xmlDoc = New XmlDocument()
doc.Load(strFileName)
//do all the reading stuff
Using writer = New StreamWriter(strFileName)
xmlDoc.Save(writer)
End Using
It will save your xmlDoc (in an attempt at disposing) then it should have unlocked the document which can then be deleted.
I haven't tested the code but give it a go
Thanks for all the help, it was being held open by streamreader which i had not considered to be a cause of the problem as I assumed it would have caused an error when XMLDocument used the file.
This worked for me. Setting the reference to nothing (null) to force a garbage collection.
xmlDoc = Nothing
I need download a CSV file and then read it. Here is my code:
tickerValue = "goog"
Dim strURL As String = "http://ichart.yahoo.com/table.csv?s=" & tickerValue
Dim strBuffer As String = RequestWebData(strURL)
Using streamReader = New StreamReader(strBuffer)
Using reader = New CsvReader(streamReader)
I keep getting this error: An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll Additional information: Illegal characters in path.
What am I doing wrong?
Additional Info
In another part of my program I use this code and it works fine.
Address = http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange=AMEX&render=download
Dim strBuffer As String = Historical_Stock_Prices.RequestWebData(Address)
Using streamReader = New StringReader(strBuffer)
Using reader = New CsvReader(streamReader)
Isn't my second code the same concept as my problem code?
you are giving it, essentially, a web url. somewhere in your code, it does not support the web url. it could be the streamreader. it could be the CsvReader.
what line of code does this point to?
the best bet is to save the file TO DISK, then read from disk.
UPDATE
here is an example to SAVE to disk:
using writer as new StreamWriter("C:\Test.csv")
writer.Write(strBuffer)
writer.Close()
end using
here is an example to READ from disk:
using strReader as new StreamReader("C:\Test.csv")
' this code is presumably how it works for reading into the CsvReader:
using reader as new CsvReader(strReader)
' now do your thing
end using
strReader.Close()
end using
I am trying to transform our system data (in xml format) to defined output xml file.
To create this output xml, I am planning to use XSLT version 2.0. Hence I'm using Saxon EE evaluation version (SaxonEE9-5-1-2 version)
I am trying to demonstrate this software to my team thereby buy the software and use the features and functionality of XSLT 2.0, XQuery, etc
Currently I am working on a prototype project - where I am having problem.
VB.NET Transformation code is as follows:
Dim strXSLT As String = String.Empty
Dim strXML As String = String.Empty
'Retrieve data from database as string
strXML = GetData()
Dim processor As Saxon.Api.Processor = New Saxon.Api.Processor()
Dim builder As Saxon.Api.DocumentBuilder = processor.NewDocumentBuilder()
'Retrieve XSLT file content from database as string
strXSLT = GetXSLT()
'Convert XSLT string data as memorystream
Dim byteDataXSLT() As Byte
byteDataXSLT = System.Text.Encoding.UTF8.GetBytes(strXSLT)
Dim msXSLT As New System.IO.MemoryStream(byteDataXSLT,0, byteDataXSLT.Length)
'Convert XML string data as memorystream
Dim byteDataXML() As Byte
byteDataXML = System.Text.Encoding.UTF8.GetBytes(strXML)
Dim msXML As New System.IO.MemoryStream(byteDataXML,0, byteDataXML.Length)
'Save the xml file before processing
Dim fsXML As New System.IO.FileStream("C:\Temp\XML.xml", System.IO.FileMode.OpenOrCreate)
Dim byteFileXML() As Byte
byteFileXML = msXML.ToArray()
fsXML.Write(byteFileXML, 0, byteFileXML.Length)
'Save the xsl file before processing
Dim fsXSLT As New System.IO.FileStream("C:\Temp\XSL.xslt", System.IO.FileMode.OpenOrCreate)
Dim byteFileXSLT() As Byte
byteFileXSLT = msXSLT.ToArray()
fsXSLT.Write(byteFileXSLT, 0, byteFileXSLT.Length)
Dim sURI As New Uri("file:///C:/")
builder.BaseUri = sURI
Dim input As Saxon.Api.XdmNode = builder.Build(msXML)
Dim transformer As Saxon.Api.XsltTransformer = processor.NewXsltCompiler().Compile(msXSLT).Load()
transformer.InitialContextNode = input
Dim serializer As New Saxon.Api.Serializer()
serializer.SetOutputFile(strOutputFileName)
transformer.Run(serializer)
I am getting below error on below line, only when I run through program. When I do the transformation manually i am not getting this error.
Dim transformer As Saxon.Api.XsltTransformer = processor.NewXsltCompiler().Compile(msXSLT).Load()
Error Message:
saxon9ee javax.xml.transform.TransformerConfigurationException: Failed to compile stylesheet.
But when I saved the xml and xslt memorystream to filestream and do the transformation manually, we get the desired output.
We are trying to figure out the root cause of this issue, but no luck.
Any details on this error message would be really helpful and very much appreciated.
Please let me know if you need more information.
Many Thanks in advance
Raghu
Looks like you are not seeing the error messages produced by the compiler. If you aren't running from the Console, then set the ErrorList property on the XsltCompiler, and when the exception occurs, inspect and display the errors somewhere, e.g. send them to a log file or pop up a window containing them.
Without seeing the error message, I can't begin to guess what the error might be.
on my .xsd file where I create the datatable for use in my Crystal Report (buit in with Visual Studio 2005), I have included a column (which is datatatype = 'Byte') that is supposed to hold the image for my crystal report.
However, there is always an error thrown at where I've typed COMMENT1, saying that the file is being used by another process. The file I am accessing is a mapped drive to our server.
when I try to ignore the error and press on continue, the report does show up..but without the image it was supposed to be with.
below is my complete syntax
Dim x As New Reporter
x.MdiParent = Magulang
Dim dt As New DataTable
dt.Columns.Add("EmpNo")
dt.Columns.Add("FullName")
dt.Columns.Add("Project")
dt.Columns.Add("SSS")
dt.Columns.Add("TIN")
dt.Columns.Add("EmergencyPerson")
dt.Columns.Add("EmergencyAddress")
dt.Columns.Add("EmergencyContact")
dt.Columns.Add("PicNya", System.Type.[GetType]("System.Byte[]"))
Dim middleinitial As String = MiddleName.Text.Substring(0, 1)
Dim fs As FileStream
Dim br As BinaryReader
If File.Exists(PicPath.Text) Then
'COMMENT1 : there is error here, saying that file is used by another process
fs = New FileStream(PicPath.Text, FileMode.Open)
Else
fs = New FileStream(AppDomain.CurrentDomain.BaseDirectory + "NoPhoto.jpg", FileMode.Open)
End If
br = New BinaryReader(fs)
Dim imgbyte As Byte() = New Byte(fs.Length) {}
imgbyte = br.ReadBytes(Convert.ToInt32((fs.Length)))
MsgBox(imgbyte.ToString)
dt.Rows.Add(EmpID.Text, FirstName.Text & " " & middleinitial & ". " & LastName.Text, Project.Text, SSS.Text, TIN.Text, EmergencyContact.Text, "", EmergencyContactNo.Text, imgbyte)
br.Close()
fs.Close()
Dim rptdoc As CrystalDecisions.CrystalReports.Engine.ReportDocument
rptdoc = New HRISID1
rptdoc.SetDataSource(dt)
x.CrystalReportViewer1.ReportSource = rptdoc
ProgressForm.Hide()
x.Show()
What can I do to resolve COMMENT1? if resolved, will the image finally output in my crystal report? Am I on the right track, if I wanted to output images on my computer?
For now, we have resolved to instead pass each Data into a seperate form, then use the PRINTFORM object included with the VB Powerpacks. This is to make sure the image is also printed.
I can't help but feel this isn't the proper solution though, so if anyone can still contribute it's very much welcome.