I have been looking for a little while now and am not finding much help via MSDN resources and others.
My predicament is simple: my app needs a base directory to the Downloads folder. I am aware of the DownloadsFolder class however that is not suiting my needs currently.
How do I get the current user's Download folder path in a Windows Universal App?
Use Windows.Storage.UserDataPaths to get the path of user's download folder.
string downloadsPath = UserDataPaths.GetDefault().Downloads;
This method is introduced in build 16232, so clients with RS3(1709) or later will be able to run it.
You shouldn't obtain downloads folder path using LocalFolder, which might result in wrong folder when the user changed the default location for it.
System.Environment.ExpandEnvironmentVariables("%userprofile%/downloads/")
Is that what you need?
string localfolder = ApplicationData.Current.LocalFolder.Path;
var array = localfolder.Split('\\');
var username = array[2];
string downloads = #"C:\Users\" + username + #"\Downloads";
This will result
C:\Users\username\Downloads
The DownloadsFolder for an app now defaults to a folder withing the user's Downloads directory named after the app name (in actual fact the app name folder is simply a link to a folder named after the Package Family Name)
To get the folder name, I used the following hack (vb) to first create a dummy file in the UWP app's DownloadsFolder then using .NET code to get the directory name, and finally deleting the dummy file.
Dim o As StorageFile = Await DownloadsFolder.CreateFileAsync("dummy.txt", CreationCollisionOption.GenerateUniqueName)
Dim dirName Ss String = Path.GetDirectoryName(o.Path)
Await o.DeleteAsync(StorageDeleteOption.PermanentDelete)
Related
I am trying to delete something from my local app data, this is my code
string folder = "%LOCALAPPDATA%\\test";
Directory.Delete(folder);
The error I get is that it's trying to find The %LOCALAPPDATA% Path inside of where my project is stored, I'm not sure if I'm doing anything wrong. If you can please help!
You can use Environment.GetFolderPath to retrieve the location of the LocalAppData folder. Example:
var localAppData = System.Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
var testFolder = System.IO.Path.Combine(localAppData, "test");
I have been using the below code in one of my apps for months as an app data backup folder and recently the path returned has changed?
IStorageItem subFolder = await KnownFolders.PicturesLibrary.TryGetItemAsync("My App Name");
Used to return: C:\Users\Lenovo\Pictures\My App Name
Now it returns: C:\Users\Lenovo\OneDrive\Pictures\My App Name
Any ideas on how/why this could have happened?
This seems to work:
string picsFolder = Windows.Storage.UserDataPaths.GetDefault().Pictures;
StorageFolder picsStorageFolder = await StorageFolder.GetFolderFromPathAsync(picsFolder);
IStorageItem appFolder = await picsStorageFolder.TryGetItemAsync("My App Name");
This is probably because the user enabled auto backup in the Onedrive app. When one does it, default directories for Pictures, Documents and so on libraries change their locations. To fix this just change the location of your library.
To do so just go to This PC, right-click desired library (e.g. Pictures), select Properties and change location in the Location tab.
I have a UWP C# app, with a unit testing project. In these unit test, I want to be able to write to a text file in order to make something like snapshots in Jest.
Directory.GetCurrentDirectory() returns C:\path\to\project\bin\x64\Debug\AppX, so I made a folder in the project directory and am navigating to it, then attempting to create a file there.
[TestMethod]
public void Test()
{
var folder = Path.Combine(Directory.GetCurrentDirectory(), "../../../../Snapshots");
string data = "example data";
string filename = Path.Combine(folder, "Test.snap");
File.WriteAllText(filename, json);
}
However, this test produces a System.UnauthorizedAccessException. I went into the folder in windows and gave Everyone read/write permissions, but that didn't make any difference.
I don't want to have to run Visual Studio as an administrator. Is this possible?
I use Path.GetTempPath() to create temporary directories and files in unit tests that require physical disk access. The unit tests can run from an unknown context/location, so I found using the temp directory as a guaranteed way to create disposable files.
[TestMethod]
public void Test()
{
var folder = Path.Combine(Path.GetTempPath(), "Snapshots");
string data = "example data";
string filename = Path.Combine(folder, "Test.snap");
File.WriteAllText(filename, json);
}
Please have a look at Rob's blog here:
https://blogs.msdn.microsoft.com/wsdevsol/2012/12/04/skip-the-path-stick-to-the-storagefile/
Here is the answer from Rob:
Windows Store apps run sandboxed and have very limited access to the
file system. For the most part, they can directly access only their
install folder and their application data folder. They do not have
permission to access the file system elsewhere (see File access and
permissions for more details).
Access to other locations is available only through a broker process.
This broker process runs with the user’s full privileges, and it can
use these privileges on the app’s behalf for locations the app has
requested via capabilities, locations requested by the user via file
pickers, etc. The StorageItem encapsulates this brokerage procedure so
the app doesn’t need to deal with it directly."
In a UWP app we do not recommend path anymore. There are permission problems so broker is required when access some paths. I'm not familar with Unit Test. But if you are still using UWP function you should consider using StorageFile related API instead.
How about checking if you gave permissions to the right folder?
var folder = Path.Combine(Directory.GetCurrentDirectory(), "../../../../Snapshots");
string data = "example data";
// this variable will contain the actual folder; add a watch
// or bookmark it to check it
var actualPath = Path.GetFullPath(folder);
string filename = Path.Combine(folder, "Test.snap");
File.WriteAllText(filename, data);
Just in case, add the line below too (before File.WriteAllText); perhaps your file already exists as, I don't know, read-only:
File.SetAttributes(filename, FileAttributes.Temporary);
Is there any way I can share file to user's dropbox folder ?
What I exactly want to implement is as below:
User Click on Dropbox icon.
Then Dropbox Asks for His/Her Dropbox account details.
File from Application Saved to his/her dropbox account.
I did search dropbox API's But did not get anything which helps me to save to user's Dropbox account.
I read API Documentation ,
https://www.dropbox.com/developers-v1/core/docs#files_put
, Here i can save files to my dropbox but not to other.
please guide me on the same. thanks in advance.
I don't know if version 2 is any better for your purposes, but version 1 of the API is deprecated
If the user has their Dropbox integrated with Explorer, then I would think you can just write to the local folder and it will sync up to Dropbox as usual.
You can use the Dropbox API to have a user authorize your app to access their Dropbox account and then programmatically save files to the account. (This works even if the user doesn't have the official Dropbox app installed.)
For .NET, we recommend using the official Dropbox API v2 .NET SDK:
https://www.dropbox.com/developers/documentation/dotnet
The tutorial shows how to upload a file:
https://www.dropbox.com/developers/documentation/dotnet#tutorial
Here is the Code snippet I Used to save Dropbox. I hope this will help mates.
// Code to retrieve Dropbox Local Folder
var infoPath = #"Dropbox\info.json";
var jsonPath = Path.Combine(Environment.GetEnvironmentVariable("LocalAppData"), infoPath);
if (!System.IO.File.Exists(jsonPath)) jsonPath = Path.Combine(Environment.GetEnvironmentVariable("AppData"), infoPath);
if (!System.IO.File.Exists(jsonPath)) {
return "-2";
}
var dropboxPath = System.IO.File.ReadAllText(jsonPath).Split('\"')[5].Replace(#"\\", #"\");
string fileName = "Your FileName";
string sourcePath = Server.MapPath("Source Path Here");
string targetPath = dropboxPath;
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, "filename.extention");
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.File.Exists(destFile))
{
System.IO.File.SetLastWriteTime(destFile, DateTime.Now);
}
I am trying to get the temp directory by using:
string tempFolder = System.IO.Path.GetTempPath();
However that method does not exist. I can see all the other methods in intelliSense though.
Why is that method not available. Is there another way to get the temp folder location in a Windows Store app?
Create the temporary file in your ApplicatonData storage. You will have to generate your own filename with a guid or timestamp.
Windows.Storage.StorageFolder temporaryFolder = ApplicationData.Current.TemporaryFolder;
StorageFile sampleFile = await temporaryFolder.CreateFileAsync("dataFile.txt", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(sampleFile, formatter.Format(DateTime.Now));
A Windows Store App is sandboxed, so you are expected to read and write to folders inside your sandboxed application folder. You won't be able to write to the traditional temp folder C:\Windows\TEMP, as you probably want, and yeah you are out of luck. There are a few other locations outside of your application folder that you have access to, but in most cases your access is limited.
The KnownFolders class is how you access the following locations.
CameraRoll
DocumentsLibrary
HomeGroup
MediaServerDevices
MusicLibrary
PicturesLibrary
Playlists
RemovableDevices
SavedPictures
VideosLibrary
KnownFolders class on MSDN