How to copy *.png from appdata:/assets/images using FileSavePicker. I find this example File Save Picker - Save Edited Image (C# Metro app) but it does not work.
i have this code:
private async void OpenButton_Click(object sender, RoutedEventArgs e)
{
string path = #"\Assets\Logo.png";
StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFile file = await folder.GetFileAsync(path);
// Show the picker
FileSavePicker savePicker = new FileSavePicker();
// Set the file that will be saved
savePicker.SuggestedSaveFile = file;
savePicker.SuggestedFileName = "Logo";
savePicker.FileTypeChoices.Add("PNG", new List<string>() { ".png" });
savePicker.PickSaveFileAndContinue();
}
but he saves the file to 0 bytes
Did you try out the sample from msdn? Where did you go wrong withe one you found?
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Document";
Source:
Reference from MSDN
Save image in windows phone 8.1 using FileSavePicker
Related
I'm trying to save my text file in UWP, but It always saving to different file. By the way I'm using MVVM architecture.
My Code
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedFileName = "New Text Document";
savePicker.SuggestedStartLocation = PickerLocationId.Desktop;
savePicker.FileTypeChoices.Add("Text Document", new List<string>() { ".txt" });
savePicker.DefaultFileExtension = ".txt";
StorageFile storageFile = await savePicker.PickSaveFileAsync();
if(storageFile != null)
{
CachedFileManager.DeferUpdates(storageFile);
await FileIO.WriteTextAsync(storageFile, Document.Text);
FileUpdateStatus updateStatus = await CachedFileManager.CompleteUpdatesAsync(storageFile);
Document.FileName = savePicker.SuggestedFileName;
Document.IsSaved = true;
}
My code is always saving texts on different file. I'm trying to save my text to same file.
In UWP there is a feature called FutureAccessList. It can be used to save the token of the file, opened with the FilePicker. When you now want to save it again you can retrive the StorageFile by the token and write to it.
Add a FileToken property to your Document class:
public string FileToken { get; set; }
Now when you pick your file you add the file to the FutureAccessList:
...
StorageFile storageFile = await savePicker.PickSaveFileAsync();
if (storageFile != null)
{
CachedFileManager.DeferUpdates(storageFile);
await FileIO.WriteTextAsync(storageFile, Document.Text);
FileUpdateStatus updateStatus = await CachedFileManager.CompleteUpdatesAsync(storageFile);
Document.FileName = savePicker.SuggestedFileName;
Document.IsSaved = true;
//Add the file to the FutureAccessList to get it back later
Document.FileToken = StorageApplicationPermissions.FutureAccessList.Add(storageFile);
}
To retrive the file and save it again:
public async void SaveFile()
{
//Get the file back from the FutureAccessList by its token and write to it
StorageFile file = await StorageApplicationPermissions.FutureAccessList.GetFileAsync(Document.FileToken);
await FileIO.WriteTextAsync(file, Document.Text);
}
Now when you e.g. save your Document class to Json and retrive it after the app restarts you can still use the FileToken to write to the file. There is no need to let the user pick it again using the SaveFilePicker.
When the code above is to complicated or there is no need for this (I don't know what you need this for), you can put a StorageFile propertie directly to your Document class and put the file, that the SaveFilePicker returned in it. But this won't work when restarting the app. The user would always have to pick the file again.
I'm trying to get image picker to work, and it does, but for some reason it won't populate as an image.
var openPicker = new FileOpenPicker
{
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.PicturesLibrary
};
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
var file = await openPicker.PickSingleFileAsync();
if (file != null)
{
//Image img = new Image();
userImage.Source = new BitmapImage(new Uri(file.Path));
//await ProcessFile(file);
}
and the image is just simply:
<image name="userImage" height="500px" width="500px"/>
This isn't work because the UWP applications have permissions only for some users folders and even you need to browse their files, you need to specify it in the package.manifest of your application which folders you want to access. For simplification, you could create a copy of the file inside the application data folder and get the path from there or set the image source from the stream of the file, but be careful, the second option maybe lead some high memory usage and leaks. You can find how to avoid this here.
You can set stream as source instead of path.
var result = new BitmapImage();
using (var randomAccessStream = await file.OpenAsync(FileAccessMode.Read))
{
await result.SetSourceAsync(randomAccessStream);
}
I'm trying to make a UWP app which can export a file saved in his own storage into the document library.
In Package.appxmanifest I've inserted the following lines:
<uap:Capability Name="picturesLibrary" />
<uap:Capability Name="documentsLibrary" />
The code to get the path is this:
StorageFolder storageFolder = await KnownFolders.GetFolderForUserAsync(null /* current user */, KnownFolderId.DocumentsLibrary);
string path = storageFolder.Path + "\\" + fileName;
The code to save the file is this:
FileStream writer = new FileStream(filePath, FileMode.Create);
At this point, the program launches this exception:
Access to the path 'C:\Users\luca9\AppData\Roaming\Microsoft\Windows\Libraries\Documents.library-ms' is denied.
On my 950XL, the exception is similar:
Access to the path 'C:\Data\Users\DefApps\APPDATA\ROAMING\MICROSOFT\WINDOWS\Libraries\Documents.library-ms' is denied.
I've tryied both on Documents and Pictures libraries, but I get the same exception.
How can I solve it?
Thank you in advance,
Luca
Don't get FileStream with path - the app doesn't have privileges. As you already have StorageFolder, use it to create a StorageFile and then get stream from it with one of its methods, for example:
var file = await storageFolder.CreateFileAsync("fileName");
using (var stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
// do what you want
}
this example from Microsoft works with uwp.
https://learn.microsoft.com/en-us/windows/uwp/files/quickstart-save-a-file-with-a-picker
1. Create and customize the FileSavePicker
var savePicker = new Windows.Storage.Pickers.FileSavePicker();
savePicker.SuggestedStartLocation =
Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary;
// Dropdown of file types the user can save the file as
savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" });
// Default file name if the user does not type one in or select a file to replace
savePicker.SuggestedFileName = "New Document";
2. Show the FileSavePicker and save to the picked file
Windows.Storage.StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
// Prevent updates to the remote version of the file until
// we finish making changes and call CompleteUpdatesAsync.
Windows.Storage.CachedFileManager.DeferUpdates(file);
// write to file
await Windows.Storage.FileIO.WriteTextAsync(file, file.Name);
// Let Windows know that we're finished changing the file so
// the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
Windows.Storage.Provider.FileUpdateStatus status =
await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);
if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
{
this.textBlock.Text = "File " + file.Name + " was saved.";
}
else
{
this.textBlock.Text = "File " + file.Name + " couldn't be saved.";
}
}
else
{
this.textBlock.Text = "Operation cancelled.";
}
So I have an upload file button which opens an open file dialog and lets you select a file.
Im not connected to server or db yet so just trying to send selected files to a specific folder on my c: drive, once the file is used it will be deleted so the name of the file will always be different.
when i want to send the file path to the method that will be using it is there a way to specify just the folder its in and for the system to use the only file within that folder then.
So far my code is all over the place as ive been trying to play around with it as im new to c# but this is what its lie so far(obviously the var isnt working and sch tried to use another example I found, getting 'not all code paths return a value error for 'getVideoFile'):
public static string getVideoFile (string filePath)
{
var path= string;
path = Directory.GetFiles(#"C:\Users\siobhan\Videos\FYPVids\");
if (path != 0){
return path;
}
else
{
//put in error message for no video file detected
}
}
the button itself:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (this.btnFileUpload.HasFile)
{
this.btnFileUpload.SaveAs(#"C:\Users\siobhan\Videos\FYPVids" + this.btnFileUpload.FileName);
}
The method the file path needs to be sent to:
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = vidDetails.vidTitle;
video.Snippet.Description = vidDetails.vidDesc;
video.Snippet.Tags = new string[] { "Test", "Second" };
video.Snippet.CategoryId = "17";//category id for sport // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Snippet.ChannelId = "UCfvR-wqeoHmAGrHnoQRfs9w";
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public"; /2015\WebSites\FYP_November\IMG_6639.mp4"; // Replace with path to actual movie file.
I am developing an Universal Windows Platform app.
To continue i need the filenames from all files in one folder into a string array.
The get files Method doesnt work in UWP. I tried around with The Filepicker and Storagefolder but I dont know how to get it into a string array.
// C#
FolderPicker picker= new FolderPicker();
picker.FileTypeFilter.Add("*"); StorageFolder x = await picker.PickSingleFolderAsync();
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", x);
string[] files = Directory.GetFiles(#"path\to\Assets");
textBlock.Text = files.Length.ToString();
You can use Directory.EnumerateFiles, System.IO.Path.GetFileName and LINQ :
string[] allFileNames = Directory.EnumerateFiles(dirPath)
.Select(System.IO.Path.GetFileName)
.ToArray();
I have no access to this folder. I tried with Directory.GetFiles(dirPath) and when i check for the length it says 0. These Windows Apps are Sandboxed.
Yes you are right about this, in an UWP app, we can access to the app's local folder or some special lib like Music Library in the code behind, otherwise we need to use Folder/File Picker to let user choose to access the folder/file.
I tried around with The Filepicker and Storagefolder but I dont know how to get it into a string array.
This is a correct direction and you can do this work using StorageFolder.GetFilesAsync method like this:
private string[] filename;
private async void Button_Click(object sender, RoutedEventArgs e)
{
FolderPicker picker = new FolderPicker();
picker.SuggestedStartLocation = PickerLocationId.ComputerFolder;
picker.FileTypeFilter.Add("*"); //match all the file format
StorageFolder folder = await picker.PickSingleFolderAsync();
if (folder != null)
{
var subFiles = await folder.GetFilesAsync();
filename = new string[subFiles.Count()];
for (int i = 0; i < subFiles.Count(); i++)
{
filename[i] = subFiles.ElementAt(i).DisplayName;
textBlock.Text = textBlock.Text + "+" + filename[i]; //show the file name in a textblock
}
}
}
Using picker.FileTypeFilter.Add("*") can make the filter match all type of files in the folder, but these files will not be shown in the picker interface.