Copy whole xml file in other xml in c# - c#

I have this xml file: http://www.studiovincent.net/list.xml
I need copy whole content in other xml file.
I tryed this code:
string sourcefile = "http://www.studiovincent.net/list.xml";
string destinationfile = "test.xml";
System.IO.File.Copy(sourcefile, destinationfile);
But not work, because I get this error: URI formats are not supported.
How Can I solve this problem?

File.Copy() does not support the http:// protocol, hence the URI formats are not supported error.
You can work around this by reading in the contents of the page into a string, and then writing it to a file.
WebClient client = new WebClient();
string contents = client.DownloadString("http://www.studiovincent.net/list.xml");
// write contents to test.xml
System.IO.File.WriteAllText ("test.xml", contents);
Note that WriteAllText() will create test.xml if it doesn't exist, and overwrite it if it does. You will also want to wrap the above code in a try / catch block and catch and handle the appropriate excpetions.

I would recommend using WebClient.DownloadFile. Downloading a string and then saving it could cause problems with character set mapping.
WebClient client = new WebClient();
client.DownloadFile("http://www.studiovincent.net/list.xml", "test.xml");
This copies the file directly rather than converting the data to a string, which might do some string conversions (for example, the file is Unicode, and WebClient thinks it's UTF-8) and then copying to a file.

Related

BitmapFrame - No imaging component suitable to complete this operation was found [duplicate]

I'm downloading in image from web to save it locally. It works great with any other image formats but it this method below fails with an argument exception when I try to read a WebP image.
private static Image GetImage(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return Image.FromStream(response.GetResponseStream());
}
catch
{
return null;
}
}
How do you read .webp images in C#?
I found this other question that allows for converting between types but I do not want to do that WebP library for C#
Reason I'm not wanting to do it is because I think it might lose some quality. Besides, I want to know why is this not working.
The base class libraries won't help you to deal with WebP images. However, if you only want to save the received file to the disk, you don't have to even know that you are dealing with a WebP images. You can simply treat the received data as a binary blob and dump it to a file, for example using Stream.CopyTo and a FileStream.
The Content-Type HTTP header will give you the mime type of the file you're downloading, and the Content-Disposition header can provide you with a filename and extension (though you might have to do some parsing). You can access those using HttpWebResponse.ContentType and HttpWebResponse.Headers["Content-Disposition"].
#Trillian nailed it. Here is a code snippet for what I did based on his suggestion. Wanted to add code so not posting this as a comment.
To get just the image file extension, you can do this
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string fileExt = response.ContentType.Replace("image/", string.Empty);
To get the file name with extension, you can do the following and the do parsing like I did above. It just has some more data in it.
response.Headers["Content-Disposition"];
Once you have you file name you want to save as, create a file stream and copy the response stream into it.
FileStream fs = new FileStream(targetPath + fileName, FileMode.Create);
response.GetResponseStream().CopyTo(fs);
Assuming you app has access to the destination, image should get saved. Make sure to add try catch and handle exceptions properly. Also note that FileMode.Create will overwrite if the file already exists!

Filepath to xml within xlsx in c#

I'm doing an xslt transform of the xml within an excel file using Saxon where the transform is being done on the .rels xml file within the xlsx file. I currently have a workaround in place where I have unzipped the entire contents of the xlsx file into a seperate folder. However, for simplicity's sake my program takes the xlsx file as it's input, so I was wondering if there was a simpler way for my program to point to the xml within the xlsx file without the need to unzip the contents. I've tried pathing to file.xlsx\_rels\.rels but that doesn't seem to work. The code I'm current using for this input is
String inputFile = "file.xlsx_folder\\_rels\\.rels"
XdmNode input = processor.NewDocumentBuilder().Build(new Uri(inputFile));
but I would like to have that point directly within the xlsx.
Yes there is a simpler way, you don't need to unzip the whole file.
Instead of the file path you've passed as a parameter to the Saxon APIs Build function, pass an XmlReader or Stream instance of the uncompressed part of the xslx file.
The Open static method of System.IO.Packaging.Package can be used to get a Package instance on which you call GetStream to uncompress the part you need and return it as a Stream. Package handles files conforming to the Open Packaging Convention, like Excel's xslx format.
The code below uncompresses the package part to a Stream, uses this to create an XmlReader instance, and finally passes the XmlReader as the parameter to the Build function:
string filename = "c:\\test\\file.xslx";
string partPath = "/_rels/.rels";
Package xpsPackage = Package.Open(fileName, FileMode.Open)
Uri partUri = new Uri(partPath, UriKind.Relative);
PackagePart xpsPart = xpsPackage.GetPart(partUri);
Stream xpsStream = xpsPart.GetStream(FileMode.Open)
XmlReader xmlReader = XmlReader.Create(xpsStream);
XdmNode input = processor.NewDocumentBuilder().Build(xmlReader);

WebClient.OpenReadAsync() corrupts JSON data. Why?

I have a class in my Silverlight app that (de-)serializes JSON strings to/from an object class.
I use WebClient.OpenReadAsync to get a file that contains this JSON string:
{"FirstName":"Bob","LastName":"Underwood"}
After calling OpenReadAsync however, the retrieved string has a lot of extra characters:
"PK\n\0\0\0\0\0�u�>h��5\0\0\05\0\0\0\t\0\0\0test.json\"{\\\"FirstName\\\":\\\"Gary\\\",\\\"LastName\\\":\\\"MacDonald\\\"}\"PK\0\n\0\0\0\0\0�u�>h��5\0\0\05\0\0\0\t\0\0\0\0\0\0\0\0\0 \0\0\0\0\0\0\0test.jsonPK\0\0\0\0\0\07\0\0\0\\\0\0\0\0\0"
This is the code I'm using to download the JSON:
WebClient client = new WebClient();
client.OpenReadCompleted += client_OpenReadCompleted;
client.OpenReadAsync(new Uri("/someJsonFile.zip", UriKind.Relative));
void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e) {
if (e.Error == null) {
StreamReader reader = new StreamReader(e.Result);
string jsonString = reader.ReadToEnd().ToString();
}
else {
addMessage("Error " + e.Error.ToString());
}
}
jsonString ends up with all that extra data, so I can't deserialize it as is.
Another thing to note: the URI points to someJsonFile.zip, but it's really not zipped, when I give the file a extension like .json, or no extension, I get a error that it cannot find the file, but when I give it a extension like .zip, it finds it fine. Is there a way I can use a normal or no extension? I was wondering if this was a configuration issue.
Questions:
Am I doing something wrong in pulling this file and using StreamReader to get the string that's causing me to get all that trash data?
Do I need to do something specific to be able to use WebClient to grab a file with different extensions, like .json, or even no extension at all?
1 - That data stream certainly is a ZIP (PK is the old PKZip marker and the test.json filename is mentioned in its index as well).
Your server may be setup to serve all files compressed (or you may simply be accessing an actual zip file). Please check the server settings.
2 - As for the second question, the WebClient does not care about file types. It is just a stream of data that needs to be interpreted by something that knows what the data is (i.e. your code).
It is only the server that may be configured to serve up different files in different ways.
I was able to figure things out with my domain provider, appears to have been some configuration issues on their end.

How to download a file without extension in C#

Okay so I want to download a file from a website, but the file is lacking an extension.
(it's an image file, I know this much, but the link does not provide the actual extension)
When I use webrequest, or webclient to download the file I get a "404 file not found" exception.
WebClient wc = new WebClient();
Stream strm = wc.DownloadFile("http://some_site.some_domain/some_image.","C:/some_directory/save_name.some_extention");
Notice the lack of extention at the end of the URL.
The site in question displays the image fine in a webbrowser, but when viewing just the image there is no extension and thus it's treated an unknown file (not showing an image).
So simply put: how do I download a file if there is no extention specified?
Thanks in advance!
So you're trying to determine what extension to give the file after downloading? If the URL doesn't have one you would have to inspect the actual data of the file.
You might be able to inspect the beginning of the file and see if it matches known valid file types. For instance, PNGs seem to have 'PNG' as bytes 2-4 (at least in the ones I've inspected). By looking at that data you should be able to determine the format with a fairly high accuracy.
This would be my best suggestion, if this doesn't work I don't know how to solve you problem...
List<string> fileExtensions = new List<string>(){"png","gif","bmp","jpg"}// other known image file extensions here...
WebClient wc = new WebClient();
foreach(var extension in fileExtensions)
{
try
{ wc.DownloadFile("http://some_site.some_domain/some_image."+extension,"C:/some_directory/save_name."+extension);
break;
}
catch {}
}
This would just be a work around, I guess... Not a real solution...

how can i load the contents of an xml file at a url into a string?

how can i load the contents of an xml file at a url into a string?
eg there is an xml file at http://www.example.com/test.xml
I want the text of the xml to be assigned to a string.
How can i do that using c#?
thanks
Well, it seems to me that the fact it's XML is irrelevant - just download it as a string:
WebClient client = new WebClient();
string text = client.DownloadString(url);
Other way to get the xml file is through HttpRequest, then you can parse the XML, if that's what you need:
previous question on the matter (with code sample)

Categories

Resources