我有一个 C# Windows Phone 7.1 应用程序,它从外部 Web 服务器下载 PDF 文件,然后(尝试)将其作为文件保存到隔离存储区域。我尝试了几种不同的方法来完成这项工作,但是文件总是以大约 30% 的大小结束,当我在文本编辑器中打开它时,而不是在文件开头看到通常的“PDF”字符后跟编码的字符,我看到基本上是垃圾。我使用的测试文件应该是 161k,但是当我使用独立存储资源管理器查看文件时,它是 271k。
首先,我将文件下载到字符串中。我此时在调试器中检查了字符串,它确实包含正确的值,并且长度正确。当我尝试将其写入隔离的存储区域时,就会出现问题。我用相同的无效结果尝试了StreamWriter和BinaryWriter 。结果文件的内容似乎是一长串的垃圾字符。请注意,如果文件存在,我将删除它以防万一,然后再写出内容。下面是我使用BinaryWriter版本的代码。怎么了?
async public static Task URLToFileAsync(
string strUrl,
string strDestFilename,
IProgress<int> progress,
CancellationToken cancelToken)
{
strUrl = strUrl.Trim();
if (String.IsNullOrWhiteSpace(strUrl))
throw new ArgumentException("(Misc::URLToFileAsync) The URL is empty.");
strDestFilename = strDestFilename.Trim();
if (String.IsNullOrWhiteSpace(strDestFilename))
throw new ArgumentException("(Misc::URLToFileAsync) The destination file name is empty.");
// Create the isolated storage file.
// FileStream fs = Misc.CreateIsolatedStorageFileStream(strDestFilename);
IsolatedStorageFile isoStorage = IsolatedStorageFile.GetUserStoreForApplication();
// Delete the file first.
if (isoStorage.FileExists(strDestFilename))
isoStorage.DeleteFile(strDestFilename);
IsolatedStorageFileStream theIsoStream = isoStorage.OpenFile(strDestFilename, FileMode.Create);
FileStream fs = theIsoStream;
// If the stream writer is NULL, then the file could not be created.
if (fs == null)
throw new System.IO.IOException("(Misc::URLToFileAsync) Error creating or writing to the file named: " + strDestFilename);
BinaryWriter bw = new BinaryWriter(fs);
try
{
// Call URLToStringAsync() to get the web file as a string first.
string strFileContents = await URLToStringAsync(strUrl, progress, cancelToken);
// >>>> NOTE: strFileContents looks correct and is the correct size.
// Operation cancelled?
if (!safeCancellationCheck(cancelToken))
{
// Note. BinaryWriter does not have an Async method so we take the hit here
// to do a synchronous operation.
// See this Stack Overflow post.
// http://stackoverflow.com/questions/10315316/asynchronous-binaryreader-and-binarywriter-in-net
// >>>> NOTE: strFileContents.ToCharArray() looks correct and is the correct length.
bw.Write(strFileContents.ToCharArray(), 0, strFileContents.Length);
} // if (safeCancellationCheck(cancelToken))
}
finally
{
// Make sure the file is cleaned up.
bw.Flush();
bw.Close();
// Make sure the file is disposed.
bw.Dispose();
} // try/finally
// >>>> NOTE: output file in Isolated Storage Explorer is the wrong size and contains apparently junk.
} // async public static void URLToFileAsync