I have XML content that I am retrieving from a service and I want to write it into a text file. I am getting this XML content in a string variable.
How can I read this and write in text file? Please help. I am getting data successfully using this code:
string results = "";
using (WebClient Web = new WebClient())
{
results = Web.DownloadString(WebString.ToString());
}
I have tried some links, but they are not helping
forums.asp.net
Reading-XML-File-and-Writing-it-to-txt-format-in-C
If you want to save it in a file, don't use DownloadString to start with - just use WebClient.DownloadFile.
If you really want to fetch it in memory and then save it, you can save it with:
File.WriteAllText(filename, results);
Note that this code doesn't depend on it being XML at all... nothing you're asking is XML-specific.
Related
I have the following part of code:
let client = new WebClient()
let url = "https://..."
client.DownloadFile(Url, filename)
client.Dispose()
In which code i am performing a HttpGet method in which method i get a file excel with some data.
The method is executed correctly because i get my excel file.
The problem is that the content of my file excel is like this:
I think its because i don't pass ContentType:"application/vnd.ms-excel"
So anyone can help how can I pass that ContentType in my Client in F# ?
If you want to add HTTP headers to a request made using WebClient, use the Headers property:
let client = new WebClient()
let url = "https://..."
client.Headers.Add(HttpRequestHeader.Accept, "application/vnd.ms-excel")
client.DownloadFile(Url, filename)
In your case, I think you need the Accept header (Content-Type is what the response should contain to tell you what you got).
That said, I'm not sure if this is the problem you are actually having - as noted in the comments, your screenshot shows a different file, so it is hard to tell what's wrong with the file you get from the download (maybe it's just somewhere else? or maybe the encoding is wrong?)
I want to upload file with file upload and stock in DataBase SQLserver using framework entity , I use this code :
string strRealPath = Request.PhysicalApplicationPath;
if(FileUpload1.HasFile)
{
string fileName = FileUpload1.FileName;
FileUpload1.SaveAs(strRealPath + fileName);
//Now insert the file into the database.
}
f.photo = Convert.ToString(FileUpload1.FileBytes);
But I find anything added .I use the debugger he tell me that posted file is null
Thanks
Firstly, your form should be encrypted as multipart/form-data. Add parameter to your form tag like below:
enctype = "multipart/form-data"
Secondly you have to send file as controller parameter HttpPostedFile.
This tutorial will be useful for you. Let us know, does it work properly.
===EDIT===
When it comes to database. You have to have column of binary type (varbinary[max]), and you
should try save it there (remember about try/catch). To read content of the file, use stream reader.
Long time lurker first time poster. Working with .Net / Linq for just a few years so I'm sure I'm missing something here. After countless hours of research I need help.
I based my code on a suggestion from https:http://damieng.com/blog/2010/01/11/linq-to-sql-tips-and-tricks-3
The following code currently saves a chosen file (pdf, doc, png, etc) which is stored in an sql database to the C:\temp. Works great. I want to take it one step further. Instead of saving it automatically to the c:\temp can I have the browser prompt so they can save it to their desired location.
{
var getFile = new myDataClass();
//retrieve attachment id from selected row
int attachmentId = Convert.ToInt32((this.gvAttachments.SelectedRow.Cells[1].Text));
//retrieve attachment information from dataclass (sql attachment table)
var results = from file in getFile.AttachmentsContents
where file.Attachment_Id == attachmentId
select file;
string writePath = #"c:\temp";
var myFile = results.First();
File.WriteAllBytes(Path.Combine(writePath, myFile.attach_Name), myFile.attach_Data.ToArray());
}
So instead of using File.WriteAllBytes can I instead take the data returned from my linq Query (myFile) and pass it into something that would prompt for the user to save the file instead?). Can this returned object be used with response.transmitfile? Thanks so much.
Just use the BinaryWrite(myFile.attach_Data.ToArray()) method to send the data since it is already in memory.
But first set headers appropriately, for example:
"Content-Disposition", "attachment; filename="+myFile.attach_Name
"Content-Type", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Content-type guides the receiving system on how it should handle the file. Here are more MS Office content types. If they are known at the point the data is stored, the content-type should be stored, too.
Also, since the file content is the only data you want in the response, call Clear before and End after BinaryWrite.
I know this must be a rookie question, but how do i accomplish that?
Because from what i have seen here : http://msdn.microsoft.com/en-us/library/system.io.streamwriter or at XMLWriter is not helping me, because i just want to save all, not write specific lines.
Basically i have an httpRequest that returns back an XML response. I am getting that in a stream, and from that i want to save it to an xml file, for later use.
Part of the code:
HttpWebResponse response = (HttpWebResponse)httpRequest.EndGetResponse(asynchronousResult);
Stream streamResponse = response.GetResponseStream();
StreamReader streamRead = new StreamReader(streamResponse);
string responseString = streamRead.ReadToEnd();
XDocument blabla = XDocument.Parse(responseString);
// Here is where the saving to a file should occur
streamResponse.Close();
streamRead.Close();
Why do you need to parse the file? In .NET 4 you can just write it directly to disk using a file stream like this:
using (var fileStream = File.Create("file.xml"))
{
streamResponse.CopyTo(fileStream);
}
If you are using an earlier version of the .NET framework, you can use the method described here to copy data from one stream to another.
Have a look at this:
http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.save.aspx
Should help you get the job done!
As you already have the XML response as a string, I think what you need is to use a StreamWriter class to write the response string straight to a file.
There is an MSDN example of its use here: How to: Write Text to a File
I've written an ASHX generic handler to output XML. However, for some reason, ASP.net is appending numerous whitespace characters to the end of the output which breaks the XML.
My code looks like this:
context.Response.ContentType = "text/xml";
XmlSerializer oSerializer = new XmlSerializer(typeof(ModelXml[]),new XmlRootAttribute("rows"));
System.IO.MemoryStream ms2 = new System.IO.MemoryStream();
System.Xml.XmlTextWriter tw = new System.Xml.XmlTextWriter(ms2,new System.Text.UTF8Encoding());
oSerializer.Serialize(tw,models);
string s = System.Text.Encoding.UTF8.GetString(ms2.GetBuffer());
tw.Close();
ms2.Close();
context.Response.Write(s.Trim());
context.Response.End();
When I run this code thru the debugger, I see that the string s does indeed contain the XML data with NO WHITESPACE. However, when I point Internet Explorer at this file, I get the following error:
The XML page cannot be displayed
Cannot view XML input using XSL style sheet. Please correct the error and then click the Refresh button, or try again later.
--------------------------------------------------------------------------------
Invalid at the top level of the document. Error processing resource 'http://localhost:5791/XXXXX.ashx'.
When I view the page source in Notepad, I see that the file begins with the correct XML, but there are numerous spaces appended to the end. If I remove these spaces, the XML file works fine with my browser and applications.
Why is ASP.net appending these spaces to my output and what can I do about it?
Switch from MS2.GetBuffer() to MS2.ToArray(). You are reading the buffer from the MemoryStream, which is preallocated for efficiency. You want just the used data, not the whole buffer.
Instead of serializing to a MemoryStream, you should serialize directly to Response.Output.
This should solve the issue.