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
Related
In an existing Asp.Net application, we are using Response.BinaryWrite to render image on an aspx page. This is the required functionality, and below is the C# code-
1. byte[] img = getImage();
2. Response.BinaryWrite(img);
The getImage function reads the image from a folder on server and returns byte array. Fortify scan shows cross-site vulnerability on 2nd line.
I did following validations, but fortify still reports it as cross-site issue -
Validated bytearray to check if the file is of correct format (jpeg or bmp), used this link - Determine file type of an image
Response.BinaryWrite(ValidateFileType(img));
Validated the domain in the file path to check if the file is originating from correct domain.
Is there any specific way to pass the fortify cross-site issue with byte array or can i consider it as false positive?
Had to use a workaround to resolve this, below is the old and new code -
Old Code -
1. byte[] byteImage = getImage();
2. Response.BinaryWrite(byteImage);
New Code (Replaced 2nd line in old code with below block) -
byte[] byteImage = getImage();
var msIn = new MemoryStream(byteImage);
System.Drawing.Image img = System.Drawing.Image.FromStream(msIn);
var msOut = new MemoryStream();
img.Save(msOut, img.RawFormat);
Response.BinaryWrite(msOut.ToArray());
msIn.Dispose();
msOut.Dispose();
Response.Flush();
So, basically converting the byteArray to an Image object, and then writing the image object back to the Response.BinaryWrite stream resolved this, and it passed through Fortify scan.
If anyone is looking for a solution, this might help.
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 am creating custom timer job service in SharePoint 2010 using asp.net 3.5 and c#.In this service, business logic is that i have to create zip file containing list of applications as excel report for each client.for this, i am using Ionic.zip third party dll and ZipFile class for creating zip file and storing this zip file on hard disk having some path.here scenario is that my code contains two foreach loops, upper for list of clients and inner for list of applications.each client may have no. of applications.I am adding these applications to zip file, storing it on hard disk and attaching this file to mail for sending to clients, but my problem is that I am trying to delete zip file before gone to next client, so that there should not be any files on hard disk, but I am getting error as "The process cannot access the file because it is being used by another process".also I have tried to attach output stream for excel report as mail attachment but I am getting zero bytes in attachment. how should i overcome this error.
I am giving simple code below
foreach(list of clients)////may have no. of clients
{
string zipFileDownloadPath = String.Empty;
foreach(list of applications)//may have no. of applications
{
HttpWebResponse resp = (HttpWebResponse)httpReq.GetResponse();
Stream excelReport = resp.GetResponseStream();
zipFile.AddEntry(appName, excelReport);
}
zipFileDownloadPath = clientFolder + #"\" + client["client_name"] + "_" + reportDate + ".zip";
zipFile.Save(zipFileDownloadPath);
mail.Attachments.Add(new Attachment(zipFileDownloadPath));
smtp.Send(mail);//mail have body, subject etc.
//here I am deleting files
if (Directory.Exists(clientFolder))
{
Directory.Delete(clientFolder, true);//here I am getting error
}
}
I the above code I have also tried so save zipfile to output stream so that there should not be any need for storing files on hard disk and attach this stream to mail attachment, but problem is that, i am getting proper bytes in output stream but when mail is sent, i am getting zero byes in attachment.
//here is code for attaching output stream to mail
foreach(list of clients)////may have no. of clients
{
foreach(list of applications)//may have no. of applications
{
HttpWebResponse resp = (HttpWebResponse)httpReq.GetResponse();
Stream excelReport = resp.GetResponseStream();
zipFile.AddEntry(appName, excelReport);
}
Stream outputStream = new MemoryStream();
zipFile.Save(outputStream);
mail.Attachments.Add(new Attachment(outputStream,"ZipFileName" MediaTypeNames.Application.Zip);));
smtp.Send(mail);//mail have body, subject etc.
}
Try moving the position of the stream to it's begiining before sending it to the attachement:
outputStream .Seek(0, SeekOrigin.Begin);
Also before deleting your file make sure you dispose the zipFile object:
zipFile.Dispose()
Or alternately (better) wrap it in a using statement.
Also unless I am missing something if you are using streams, why do you need to save the files to the harddrive? just use the streams, something along the lines of:
var ms = new new MemoryStream();
zipFile.Save(ms);
ms.Seek(0, SeekOrigin.Begin);
mail.Attachments.Add(new Attachment(ms,"ZipFileName" MediaTypeNames.Application.Zip));
zipFile.Dispose()
Special thanks to Luis.Luis has solved my problem.
Hi Everyone Finally I have solved my problem. problem was that I was saving the zip file on output stream so stream was reading exact bytes and reaching at it's last position and I was attaching same stream to attachment that's why i was getting zero bytes in mail attachment.so solution for this is that seek the position of output stream to begin after saving to zip file and before attaching to it to mail. please refer following code for reference.
Stream outputStream = new MemoryStream();
zipFile.Save(outputStream);
outputStream .Seek(0, SeekOrigin.Begin);
mail.Attachments.Add(new Attachment(outputStream,"ZipFileName" MediaTypeNames.Application.Zip);));
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.
I have a FileUpload control. I am trying to save the file that is uploaded (an image) and also save several thumbnail copies of the file.
When I try something like this:
System.Drawing.Image imgOriginal = System.Drawing.Image.FromStream(PhotoUpload.PostedFile.InputStream);
I get an "System.ArgumentException: Parameter is not valid."
I also tried using the PhotoUpload.FileBytes to create the image from the file bytes instead of the InputStream, but the same error occurs.
The uploaded file is a jpg. I know it's a valid jpg since it saves the original ok.
Edit: This code actually does work. The Parameter is not valid was due to the PhotoUpload.PostedFile.InputStream being empty... which seems to be an entirely different issue. It looks like after I save the original the fileupload stream goes away.
Edit: Found out that the InputStream of a FileUpload can only be read/consumed one time and then it is gone.
To get around that I saved the fileupload filebytes into a byte array and used the byte array to create copies of the image.
Code:
// Copy the FileBytes into a byte array
byte[] imageData = PhotoUpload.FileBytes;
// Create a stream from the byte array if you want to save it somewhere:
System.IO.Stream myStream = new System.IO.MemoryStream(imageData);
// Or create an image from the stream as many times as needed:
System.Drawing.Image imgOriginal = System.Drawing.Image.FromStream(myStream);
Have a look at this link
ASP Net - How to pass a postedfile to a system.drawing.image
Here's my function call:
uploadAndSizeImage(System.Drawing.Image.FromStream
(uploadedFileMD.PostedFile.InputStream))
I'm getting this error:
Exception Details:
System.ArgumentException: Invalid
parameter used.
Google isn't turning up much though I
did find a reference to it possibly
being caused by the stream reader
being at the end of the stream and me
needing to reset it to position one.
But that was kind of vague and not
really sure if it applies here.
Does this help?
EDIT:
Also, have you tried manually reading the file using something like
System.IO.FileStream fs = System.IO.File.OpenRead(#"Image.JPG");
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
System.Drawing.Image image = Image.FromStream(ms);
Or saving a temp copy from the FileUpload and loading the image from file?