What is wrong here? It throws ArgumentException
var xmlDocument = await XmlDocument.LoadFromUriAsync(new Uri("ms-appx:///LiveTiles/Templates.xml"));
Is there more simple way to load XML from file?
Thank you!
Windows RT is a little bit special at the time of manipulating files, I highly recommend this blog entry:
http://blog.jerrynixon.com/2012/06/windows-8-how-to-read-files-in-winrt.html
Taken from the link:
// settings
// same as (ms-appx:///MyFolder/MyFile.txt)
var _Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
_Folder = await _Folder.GetFolderAsync("MyFolder");
// acquire file
var _File = await _Folder.GetFileAsync("MyFile.txt");
Assert.IsNotNull(_File, "Acquire File");
// write content
var _WriteThis = "Hello World";
await Windows.Storage.FileIO.WriteTextAsync(_File, _WriteThis);
Or to simplify it a little bit more, another approach can be:
try
{
StorageFolder storageFolder = Package.Current.InstalledLocation;
StorageFile storageFile = await storageFolder.GetFileAsync("BasicData.xml");
XmlTextBlock.Text = await FileIO.ReadTextAsync(storageFile, Windows.Storage.Streams.UnicodeEncoding.Utf8);
}
catch (Exception ex)
{
XmlTextBlock.Text = ex.Message;
}
Related
The Excel file that I'm trying to upload to blob is not getting created properly although it is getting uploaded successfully. I'm using the UploadBlobAsync for the same.
private async Task UploadExcelToBlobAsync(string fileName, MemoryStream excelContentMemoryStream)
{
try
{
string currentDateTime = DateTime.Now.ToString("dd-MM-yyyy_HH-mm-ss");
string fileExtension = ".xslx";
fileName = $"{fileName}_{currentDateTime}{fileExtension}";
var blobContainerClient = _blobService.GetBlobContainerClient(); // this is properly instatiated
await blobContainerClient.UploadBlobAsync(fileName, excelContentMemoryStream);
}
catch (Exception ex)
{
throw ex;
}
}
Strangely though, the same MemoryStream object I'm using further in my code to perform some logic. So I guess, the issue is not with the MemoryStream object also. Below is a snip of the generated Excel, the generated file size is 14KB while the one that I had uploaded was of 20KB:
Can someone please tell me what I'm possibly doing wrong here? Many thanks in advance.
Addition: Below is the code which calls the method UploadExcelToBlobAsync:
public async Task<(string, List<CustomObject>?)> UploadExcelAsync(IFormFile file)
{
try
{
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
using (MemoryStream ms = new MemoryStream())
{
await file.CopyToAsync(ms);
var excelReader = ExcelReaderFactory.CreateOpenXmlReader(ms);
DataSet excelDataSet = excelReader.AsDataSet();
await UploadExcelToBlobAsync(file.FileName, ms);
var resp = await ValidateAndInsertExcelData(excelDataSet);
return resp;
}
}
catch(Exception ex)
{
throw ex;
}
}
Please try my code, if the downloaded file does not appear that prompt, my suggestion is to use my sample code.
[HttpPost]
[Route("UploadExcel")]
public async Task<IActionResult> UploadExcelAsync([FromForm] IFormCollection formfile)
{
string sasuri = "https://br***nWTT5GnC1LpHsD7p5Fo2lHpFM1nafAHjL9Fozf%2FvDdg%3D";
Uri container_uri = new Uri(sasuri);
var container_client = new BlobContainerClient(container_uri);
var file = formfile.Files.FirstOrDefault();
string fileName = file.FileName;
BlobClient blobClient = container_client.GetBlobClient(fileName);
Stream stream = file.OpenReadStream();
var result = await blobClient.UploadAsync(stream, true);
stream.Close();
return Ok(result.GetRawResponse().Status);
}
If you use my sample code, there is still such a prompt:
The file could be corrupted or unsafe. Unless you trust its source, don't open it.
Then please try to use another computer as client for test. If the issue still exists. It means the Microsoft office version or scurity has some problem. Then try this.
I am writing text to a file in Windows Phone 8.1 like this:
private static async Task WriteData(String fileName, String content)
{
Byte[] data = Encoding.Unicode.GetBytes(content);
var folder = ApplicationData.Current.LocalFolder;
var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (var s = await file.OpenStreamForWriteAsync())
{
await s.WriteAsync(data, 0, data.Length);
}
}
But when I read the file, it comes back empty. I have verified that there isn't some other method overwriting it by reading from the file immediately after I write to it. Am I missing something obvious here?
Maybe you can try:
public async Task SaveStreamToFile(Stream streamToSave, string fileName, CancellationToken cancelToken)
{
Byte[] buf= Encoding.Unicode.GetBytes(content);
var folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream fileStram = await file.OpenStreamForWriteAsync())
{
int bytesread = 0;
while ((bytesread = await streamToSave.ReadAsync(buf, 0, BUFFER_SIZE)) > 0)
{
await fileStram.WriteAsync(buf, 0, bytesread);
cancelToken.ThrowIfCancellationRequested();
}
}
}
I was having the same problem. I save 2 files, one with debug information, and one with application specific information (a list of routes).The debug information seems to work OK
StorageFolder local = ApplicationData.Current.LocalFolder;
var file = await local.CreateFileAsync "debug.txt",CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, sbDebugInformation.ToString());
but the CreateCollisionOption.ReplaceExisting seemed to be causing problems with the other information, and I ended up with this, after many alternate attempts
StorageFolder local = ApplicationData.Current.LocalFolder;
var json = new DataContractJsonSerializer(typeof(RouteList));
var file = await local.CreateFileAsync(filename,CreationCollisionOption.OpenIfExists);
MemoryStream stream = new MemoryStream();
json.WriteObject(stream, routes);
await FileIO.WriteBytesAsync(file, stream.ToArray());
I'm trying to launch pdf reader with the code below but it does not work. Can somebody help me?
private async Task<StorageFile> WriteData(string fileName, byte[] data)
{
StorageFolder folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream s = await file.OpenStreamForWriteAsync())
{
await s.WriteAsync(data, 0, data.Length);
s.Close();
}
return file;
}
private async Task<bool> OpenPdf(StorageFile file)
{
var uri = new Uri(file.Path, UriKind.RelativeOrAbsolute);
bool result = await Windows.System.Launcher.LaunchUriAsync(uri);
return result;
}
private async void FetchPdf() {
// Fetch pdf bytes to network
//....
StorageFile file = await WriteData("test.pdf", data);
if (file != null) {
bool result = await OpenPdf(file);
if (result)
Debug.WriteLine("Success");
else
Debug.WriteLine("Cannot open pdf file.");
}
}
result is always false and so launcher is not presented.
I used LaunchUriAsync because LaunchFileAsync is not implemented on Windows Phone.
LaunchUriAsync isn't supported on Windows Phone 8 per the documentation. It throws an exception if called
You can use Windows.System.Launcher.LaunchFileAsync to launch a StorageFile.
This code works for example (assming there's a file called "metro.pdf" in the project, with the Build Action set to Content, with Copy to Output Directory set to Copy if Newer).
var installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
var assets = await installedLocation.GetFolderAsync("Assets");
var pdf = await assets.GetFileAsync("metro.pdf");
Windows.System.Launcher.LaunchFileAsync(pdf);
Called the API and saved the byte array to file
public static async void WriteDataToIsolatedStorageFile(string fileName, byte[] data)
{
using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = storageFile.OpenFile(fileName, FileMode.Create))
{
if ((data != null) && (data.Length > 0))
{
await stream.WriteAsync(data, 0, data.Length);
}
}
}
}
opened the file in pdf reader using
private async void StartExternalPDFApp()
{
StorageFolder localFolder = await FileManager.FindDirectory(FileManager.RelativeStorageDirectoryLocalStorage);
StorageFile storageFile = await localFolder.GetFileAsync(PdfFileName);
await Windows.System.Launcher.LaunchFileAsync(storageFile);
}
localFolder is Windows.Storage.ApplicationData.Current.LocalFolder
just put the anyFile.pdf in Assets folder, and make its build action to Content, and then Just make the function Async ... and then Put "await" before Windows.System.Launcher.LaunchFileAsync(pdf);
it worked fine for me. Nice.
See this.
private async void privacyPolicy_Click(object sender, EventArgs e)
{
var installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation;
var assets = await installedLocation.GetFolderAsync("Assets");
var pdf = await assets.GetFileAsync("PrivacyPolicy.pdf");
await Windows.System.Launcher.LaunchFileAsync(pdf);
}
I'm creating a windows rt application which contains more than 1000 .txt files from which I'm getting their contents.
These text files are part of my project but I can't read them with code.
This is my code
static async Task ReadFile(string filePath, List<string> list)
{
try
{
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///" + filePath));
var readThis = await FileIO.ReadLinesAsync(file);
foreach (var line in readThis)
{
list.Add(line);
}
}
catch (FileNotFoundException)
{
}
}
where filePath is : "txt/data/14b.txt.
When code is executed Lists are filled with the data but application crashes and I'm sent in this line of app.g.i.cs
if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break();
any ideas ?
Try marking your text files Build Action as Content. Then
var file = await StorageFile.GetFileFromApplicationUriAsync( new Uri( "ms-appx:///" + filePath ) );
Should load a file.
var storageFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri(String.Format("ms-appx:///{Project name}/txt/data/{0}", fileName)));
Try with replacing
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///" + filePath));
to
var ProjectFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFile file = await ProjectFolder.GetFileAsync(fileName);
I'm working in VS2012, WinRT and C#.
I'm trying to delete some files after decompressing them. I'm getting an "Access is denied" error. If I stop the app and re-start it the same code works fine so it appears there is a handle still attached.
If I don't call the unZipFile method, I can delete the files.
Is there a definitive way to release a file? I've set it to null (file = null;) before the call to delete.
Here's the block of code that calls the unzip method:
StorageFile file = await CreateOutputFile(fileName, path);
MemoryStream theMemStream = new MemoryStream();
theMemStream.Write(bytes, 0, bytes.Length);
await FileIO.WriteBytesAsync(file, bytes);
await theMemStream.FlushAsync();
theMemStream.Dispose();
var result = await unZipFile(file, path);
file = null;
Here's the unZipFile method:
private async Task<string> unZipFile(StorageFile file, string path)
{
StorageFolder sf = await GetOutputFolder(path);
using (var zipStream = await file.OpenStreamForReadAsync())
{
using (MemoryStream zipMemoryStream = new MemoryStream((int)zipStream.Length))
{
await zipStream.CopyToAsync(zipMemoryStream);
try
{
var archive = SharpCompress.Archive.ArchiveFactory.Open(file.Path);
foreach (var entry in archive.Entries)
{
entry.WriteTo(zipMemoryStream);
Stream fileData = entry.OpenEntryStream();
StorageFile outputFile = await sf.CreateFileAsync(entry.FilePath, CreationCollisionOption.ReplaceExisting);
using (Stream outputFileStream = await outputFile.OpenStreamForWriteAsync())
{
await fileData.CopyToAsync(outputFileStream);
await outputFileStream.FlushAsync();
outputFileStream.Dispose();
}
}
archive = null;
}
catch (Exception ex)
{
throw new IOException("Error writing decompressed output file: " + ex.Message);
}
await zipStream.FlushAsync();
zipStream.Dispose();
await zipMemoryStream.FlushAsync();
zipMemoryStream.Dispose();
}
}
return "success";
}
Here's the delete method. This is called for each file after decompression:
private async Task<string> deleteFile(string path, string filename)
{
StorageFolder folder = await GetOutputFolder(path);
var files = await folder.GetFilesAsync();
foreach (StorageFile file in files)
{
try
{
if (file != null)
{
if (file.Name == filename)
await file.DeleteAsync();
}
}
catch (Exception ex)
{
return ex.Message;
}
}
return "success";
}
On what file do you get the exception, the extracted files or the zip archive itself?
If the latter is the case, ArchiveFactory.Open() returns an IArchive which inherits IDisposable, so you should wrap var archive = SharpCompress.Archive.ArchiveFactory.Open(file.Path); in a using block so it gets disposed after use.