Data at the root level is invalid. Line 1, position 1 - c#

I am downloading a xml file from the internet and save it in isolated storage. If I try to read it I get an error:
Data at the root level is invalid. Line 1, position 1.
string tempUrl = "http://xxxxx.myfile.xml"; // changed
WebClient client = new WebClient();
client.OpenReadAsync(new Uri(tempUrl));
client.OpenReadCompleted += new OpenReadCompletedEventHandler(delegate(object sender, OpenReadCompletedEventArgs e) {
StreamWriter writer = new StreamWriter(new IsolatedStorageFileStream("myfile.xml", FileMode.Create, FileAccess.Write, myIsolatedStorage));
writer.WriteLine(e.Result);
writer.Close();
});
This is how I download and save the file...
And I try to read it like that:
IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("myfile.xml", FileMode.Open, FileAccess.Read);
XDocument xmlDoc = XDocument.Load(fileStream);
This is where I get the error...
I have no problem reading the same file without downloading and saving it to isolated storage... so there must be the fault.

This:
writer.WriteLine(e.Result);
doesn't do what you think it does. It's just calling ToString() on a Stream, and writing the result to a file.
I suggest you avoid using a StreamWriter completely, and simply copy from e.Result straight to the IsolatedStorageFileStream:
using (var output = new IsolatedStorageFileStream("myfile.xml", FileMode.Create,
FileAccess.Write, myIsolatedStorage))
{
CopyStream(e.Result, output);
}
where CopyStream would be a method to just copy the data, e.g.
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int read;
while((read = input.Read (buffer, 0, buffer.Length)) > 0)
{
output.Write (buffer, 0, read);
}
}

Related

Error "file in use" when playing aac while appending bytes to aac

var outputfile = "outputfile.aac";
var fileList = new List<string>
{
"1.aac",
"2.aac",
"3.aac",
"4.aac",
"5.aac",
"6.aac"
};
foreach (var file in fileList)
{
using (var stream = new FileStream(outputfile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
var bytes = File.ReadAllBytes(file);
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
}
}
I try to join aac files in fileList into outputfile. when writing file "3.aac" to outputfile.aac, I open outputfile with MediaPlayer, then the FileStream returns exception "file in use", even FileShare mode is ReadWrite, it means that other processes can read and write to the file. So where is the reason?
However, in this case output file is not blocked
Stream s = resp.GetResponseStream();
var fs = File.Exists(outputFile) ? new FileStream(outputFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)
: new FileStream(outputFile, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
byte[] buffer = new byte[4096];
while (s.CanRead)
{
int bytesRead = s.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, bytesRead);
}
P/s: I found that the reason because it's aac file
When you use FileShare.ReadWrite you allow subsequent opening of the file in read or write mode.
MediaPlayer then opens the file with FileShare.Read on its side, denying you write access to the file.

Can't Write from FileStream

I am trying to get a byte[] from a FileInfo.
Here, The FileInfo(fi) is a file I drop into my silverlight app.
So, as found on msnd, I am doing this :
byte[] b = new byte[fi.Length];
UTF8Encoding temp = new UTF8Encoding(true);
//Open the stream and read it back.
using (FileStream fs = fi.OpenRead())
{
while (fs.Read(b, 0, b.Length) > 0)
{
Console.WriteLine(temp.GetString(b));
}
}
But, do to it's protection level, I cannot use this.
So, I have done this :
byte[] b = new byte[fi.Length];
UTF8Encoding temp = new UTF8Encoding(true);
//Open the stream and read it back.
using (FileStream fs = fi.OpenRead())
{
while (fs.Read(b, 0, b.Length) > 0)
{
fs.Write(b, 0, b.Length);
}
}
But I got the message that I cannot Write from the FileStream.
Why I cannot write my File I drop into my app into a byte?
When The File is drop, it become a FileInfo.
Why I use OpenRead()? Because on the msdn, it seems it is writing the file : here
OpenWrite() rise an access error also.
Is there another way to do get yhe FileInfo document, into a byte?
To read a file into a byte[] the easies way would be:
byte[] myByteArray = File.ReadAllBytes(myFileInfo.FullName);
As #Dmitry Bychenko allready stated you try to write to a FileStream opened as readonly.
The other thing is that you want to write to the same FileStream you read from.
To solve the problem by correcting the attempt you did you can do:
byte[] b = new byte[fi.Length];
UTF8Encoding temp = new UTF8Encoding(true);
//Open the stream and read it back.
using (FileStream fs = fi.OpenRead())
{
using (MemoryStream ms = new MemoryStream(b))
{
while (fs.Read(b, 0, b.Length) > 0)
{
ms.Write(b, 0, b.Length);
}
}
}
In your case i would vote for the first example as its simple to read and hides the stream stuff perfectly.

C# write an uploaded file to a UNC with FileStream, read it later sometimes doesn't work

I've got a rare case where a file cannot be read from a UNC path immediately after it was written. Here's the workflow:
plupload sends a large file in chunks to a WebAPI method
Method writes the chunks to a UNC path (a storage server). This loops until the file is completely uploaded.
After a few other operations, the same method tries to read the file again and sometimes it cannot find the file
It only seems to happen after our servers have been idle for a while. If I repeat the upload a few times, it starts to work.
I thought it might be a network configuration issue, or something to do with the file not completely closing before being read again.
Here's part of the code that writes the file (is the filestream OK in this case?)
SaveStream(stream, new FileStream(fileName, FileMode.Append, FileAccess.Write));
Here's SaveStream definition:
private static void SaveStream(Stream stream, FileStream fileStream)
{
using (var fs = fileStream)
{
var buffer = new byte[1024];
var l = stream.Read(buffer, 0, 1024);
while (l > 0)
{
fs.Write(buffer, 0, l);
l = stream.Read(buffer, 0, 1024);
}
fs.Flush();
fs.Close();
}
}
Here's the code that reads the file:
var fileInfo = new FileInfo(fileName);
var exists = fileInfo.Exists;
It's the fileInfo.Exists that is returning false.
Thank you
These kind of errors are mostly due to files not closed yet.
Try passing the fileName to SaveStream and then use it as follows:
private static void SaveStream(Stream stream, string fileName)
{
using (var fs = new FileStream(fileName, FileMode.Append, FileAccess.Write))
{
var buffer = new byte[1024];
var l = stream.Read(buffer, 0, 1024);
while (l > 0)
{
fs.Write(buffer, 0, l);
l = stream.Read(buffer, 0, 1024);
}
fs.Flush();
} // end of using will close and dispose fs properly
}

Uploading zip file with POST/httpwebrequest in C#

I'm trying code from http://www.paraesthesia.com/archive/2009/12/16/posting-multipartform-data-using-.net-webrequest.aspx to do a POST through httpwebrequest.
If I try this same code with a text file, it's fine. However if I do it with a zip file, then when re-download that file it's saying it's not a valid zip. I assume the zip portion is likely getting uploaded as text rather than binary. However, that page does say " It's OK to include binary content here. Don't base-64 encode it or anything, just stream it on in." But this doesn't seem to be working with the given code. I'm assuming I have to change the portion that reads the file to the stream:
using (FileStream fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
fileStream.Close();
}
Maybe to use BinaryReader? I'm a bit confused on how to use that in this context though, or if it's even what I need to do. A nudge in the right direction would be awesome. Thanks!
BinaryReader should work indeed:
FileInfo fInfo = new FileInfo(file.FullName);
//
long numBytes = fInfo.Length;
FileStream fStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
byte[] bdata = br.ReadBytes((int)numBytes);
br.Close();
fStream.Close();
// Write bdata to the HttpStream
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("url-here");
// Additional webRequest parameters settings.
HttpStream stream = (Stream)webRequest.GetRequestStream();
stream .Write(bdata, 0, bdata.Length);
stream.Close();
HttpWebResponse response = (HttpWebRewponse)webRequest.GetResponse();

How to save MP3 file from the internet on Windows Phone 7?

I'm trying to download and save an .mp3 file from the internet, but got stuck with stream from the external link:
private void saveSound()
{
IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
using (var fs = new IsolatedStorageFileStream("123.mp3", FileMode.Create, iso))
{
//Here should be this Stream from the Internet...
//Uri: "http://my-site.com/mega-popular-song.mp3"
StreamResourceInfo rs = new StreamResourceInfo(stream, "audio/mpeg");
int count = 0;
byte[] buffer = new byte[4096];
while (0 < (count = rs.Stream.Read(buffer, 0, buffer.Length)))
{
fs.Write(buffer, 0, count);
}
fs.Close();
}
}
What should this stream look like? What is the best way to download and save .mp3 files?
I'm sure this article gets you there. Like Bob mentioned, you'll have to use a WebClient. Basically this is the code that does the magic:
wc.OpenReadCompleted += ((s, args) =>
{
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
if (store.FileExists(fileName))
store.DeleteFile(fileName);
using (var fs = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
{
byte[] bytesInStream = new byte[args.Result.Length];
args.Result.Read(bytesInStream, 0, (int)bytesInStream.Length);
fs.Write(bytesInStream, 0, bytesInStream.Length);
fs.Flush();
}
}
});
But I would read the complete article to fully understand what happens. Hope this helps!

Categories