I am trying to load a pdf file from a folder in my win8 app. It is in the test folder. I try
StorageFile file = StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Test/example.pdf"));
That gives me a file not found. However, if I change the extension of example.pdf to jpg, then change the code to look for example.jpg, it does work properly. What is going on?
Try this:
public async Task<StorageFile> GetFileAsync(string directory, string fileName)
{
string filePath = BuildPath(directory, fileName);
string directoryName = Path.GetDirectoryName(filePath);
StorageFolder storageFolder = await StorageFolder.GetFolderFromPathAsync(directoryName);
StorageFile storageFile = await storageFolder.GetFileAsync(fileName);
return storageFile;
}
public string BuildPath(string directoryPath, string fileName)
{
string directory = Path.Combine(Package.Current.InstalledLocation.Path, directoryPath);
return Path.Combine(directory, fileName);
}
From your client, pass-in the directory (relative to the project) path of the file and then supply the file name for the second parameter.
In addition, it's probably good that you just create a library to manage various file operations.
Related
I'm using FileIO to append Json data in a LocalStorage file.
public static async Task AppendToJsonLocalStorage<T>(string filename, T objectToWrite) where T : new()
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile saveFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
await FileIO.AppendTextAsync(saveFile, contentsToWriteToFile);
}
AppendTextAsync should only add new text at the end of the existing file, wright ?
Because when I check the file in my file explorer with a text editor it's always overwriting the former text in it.
Use CreationCollisionOption.OpenIfExists instead of CreationCollisionOption.ReplaceExisting when you create the file:
StorageFile saveFile = await localFolder.CreateFileAsync(filename, CreationCollisionOption.OpenIfExists);
var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite);
await FileIO.AppendTextAsync(saveFile, contentsToWriteToFile);
ReplaceExisting replaces any existing file as the name suggests. Please refer to the docs for more information.
Here is my code........
public MediaPlaybackItem GetMediaPlaybackItemFromPath(string path)
{
//StorageFile file = await StorageFile.GetFileFromPathAsync(path);
var source = MediaSource.CreateFromUri(new Uri(path));
return new MediaPlaybackItem(source);
}
If I use this method I cannot play music. But if I try this I can play music.
public async Task<MediaPlaybackItem> GetMediaPlaybackItemFromPathAsync(string path)
{
StorageFile file = await StorageFile.GetFileFromPathAsync(path);
var source = MediaSource.CreateFromStorageFile(file);
return new MediaPlaybackItem(source);
}
Whats the problem with this? I am using mediaplaybacklist for MediaPlayer.Source . How can I get proper MediaSource using my first method? Help me please.
You could not pass file path parameter to CreateFromUri directly. In general, the Uri parameter is http protocol address such as http://www.testvideo.com/forkvideo/test.mp4. But we could pass the file path with uwp file access uri scheme.
For example:
Media file stored in the installation folder.
ms-appx:///
Local folder.
ms-appdata:///local/
Temporary folder.
ms-appdata:///temp/
For more you could refer this document.
I want to download a folder with its files in various mime type. My virtual path is "http://localhost/attachments/". My sub folders are "certificates/id". So when clicking on a grid i pass id to the download page. But it throws an exception like virtual path is invalid. 'http://localhost/attachments/certificates/id)'.
In below code, Request.Params[0] meant id, this points the endlevel folder which i want to make a zip folder.
Any guidance would be grateful.
using (ZipFile zip = new ZipFile())
{
string VirtualPath = ConfigurationManager.AppSettings.Get("AttachmentsShowVirtualPath");
string Path = string.Empty;
Path = "certificates" + "/";
string folderPath = VirtualPath + Path + Request.Params[0] + "/";
zip.CompressionLevel = CompressionLevel.None;
zip.AddSelectedFiles(".", Server.MapPath(folderPath), "", false);
zip.Save(Response.OutputStream);
}
First, are you using DotNetZip? I have never use it, but try changing the . to *.*
If not getting the file, try to do Directory.GetFiles to check if eveything is pointing correctly and your code has read permission over the directory https://msdn.microsoft.com/en-us/library/07wt70x2%28v=vs.110%29.aspx
Or try to use official Zip class from https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile%28v=vs.110%29.aspx With this method: ZipFile.CreateFromDirectory
I have to read the text content from an .txt file, this file is located in app installed folder, in a subfolder, according to Microsoft docs, I am doing it like this:
private async void readMyFile()
{
// Get the app's installation folder.
StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
// Get a file from a subfolder of the current folder by providing a relative path.
string txtFileName = #"\myfolder\myfile.txt";
try
{
//here my file exists and I get file path
StorageFile txtfile = await appFolder.GetFileAsync(txtFileName);
Debug.WriteLine("ok file found: " + txtfile.Path);
//here I get the error
string text = await FileIO.ReadTextAsync(txtfile);
Debug.WriteLine("Txt is: " + text);
}
catch (FileNotFoundException ex)
{
}
}
the error is:
Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.ni.dll
exception file not found: System.IO.FileNotFoundException: The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Smadshop.MainPage.<testExistsFile>d__8.MoveNext()
Have to notice that if I use the file without subfolder everything is working fine.
you can do it in other way, using URI :
using Windows.Storage;
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync("ms-appx:///file.txt");
So in your case it will be:
StorageFile txtfile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///myfolder/myfile.txt"));
I think you need to use:
string txtFileName = #".\myfolder\myfile.txt";
The dot in the filename represents the current folder. In you want to specify using relative paths, then #"\myfolder\myfile.txt" is not correct.
GetFileAsync will take relative path in form folder/fileName. You can also get folder first and than file or use GetItemAsync
StorageFolder appFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;
// Get a file from a subfolder of the current folder
// by providing a relative path.
string image = #"Assets\Logo.scale-100.png";
var logoImage = await appFolder.GetFileAsync(image);
#"\myfolder\myfile.txt"; if its a network path should be #"\\myfolder\myfile.txt"; If its a local file it needs a drive letter ie.#"c:\myfolder\myfile.txt";
However the documentation for GetFileAsync shows a file in a subfolder would be #"myfolder\myfile.txt"
When you use a filename without a subfolder it will look in the current folder.
How do I open text document, .docx and .xls document in windows phone 8,
I am saving file in isolated storage then trying to open using Launcher.FileAsync but do not getting the result. For more information, see my code below:
string file = "Download.txt";
IsolatedStorageFileStream isfStream = new IsolatedStorageFileStream(file, FileMode.Create, IsolatedStorageFile.GetUserStoreForApplication());
isfStream.Close();
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile pdffile = await local.GetFileAsync(file);
Windows.System.Launcher.LaunchFileAsync(pdffile);
The syntax of GetFileAsync() is
public IAsyncOperation<StorageFile> GetFileAsync(string name)
where
name : The name (or path relative to the current folder) of the file to get.
your string is
string file = "Download.txt";
This might not be accepted as a relative path. Try something like,
string file = #"\Download.txt";