I have the following code
private static async Task CreateZipFile(string folderPath)
{
await Task.Run(() =>
{
try
{
ZipFile.CreateFromDirectory(folderPath, ApplicationData.Current.LocalFolder.Path + "backup.zip");
}
catch (Exception e)
{
;
}
});
}
In my UWP app. However I am getting access denied errors on the LocalFolder.
The directory I am trying to zip is in my LocalState folder so
folderPath = C:\Users\username\AppData\Local\Packages\MyApp_3y0bchp7kwvet\LocalState\BACKUP
Any ideas how to resolve? Other code has no problem accessing these folders.
I'd think the problem here is that you've used wrong path as destinationArchiveFileName in ZipFile.CreateFromDirectory method.
For a valid path, it should be ApplicationData.Current.LocalFolder.Path + "\\backup.zip".
Once you changed your code like the following, it should be able to work.
ZipFile.CreateFromDirectory(folderPath, ApplicationData.Current.LocalFolder.Path + "\\backup.zip");
Related
I know this is a common problem with a lot of related topics on here. But none of them seem to work for me.
I have code that works on a production system that I've copied across to my local home computer:
private static void WriteToLog(string logText, string logPath)
{
try
{
using (StreamWriter outputFile = File.AppendText(logPath))
{
outputFile.WriteLine(DateTime.Now.ToString() + "|| " + Regex.Replace(logText, #"\t|\n|\r", ""));
}
}
catch (IOException ex)
{
//what do?
throw ex;
}
}
The line using (StreamWriter outputFile = File.AppendText(logPath)) throws the classic exception:
System.UnauthorizedAccessException: 'Access to the path
'C:\Users\Jaso\Documents\DataChecker_Logs\schema_a-academic_attainment.txt'
is denied.'
At runtime the path variable contains "C:\\Users\\Jaso\\Documents\\DataChecker_Logs\\schema_a-academic_attainment.txt"
The Security of the folder in question looks like this:
When I find the user the process is run under using WindowsIdentity.GetCurrent().Name;, the value returned is "DESKTOP-LMMBET3\\Jaso" which according to the folder's settings (above screenshot) is a principal with full control!!
Windows 10 machine.
GRRR!!!
Check the permission of the file itself not the folder
if you don't have the permission to access the file this error will be thrown
System.UnauthorizedAccessException
I'm trying to use this code to access a file's URI from the PicturesLibrary:
StorageFolder picturesFolder = KnownFolders.PicturesLibrary;
StorageFile tpkFile = await picturesFolder.GetFileAsync("campus.tpk");
Uri tpkFileUri = new Uri(tpkFile.Path);
Debug.WriteLine("This is the tpkFile path: " + tpkFileUri);
ArcGISTiledLayer tpkLayer = new ArcGISTiledLayer(tpkFileUri);
try
{
MyMapView.Map.OperationalLayers.Add(tpkLayer);
}
catch(Exception e)
{
Debug.WriteLine("This is the Exception: " + e);
}
Which returns a URI of:
file:///C:/Users/username/Pictures/campus.tpk
But I know UWP apps only take URIs that start with ms-appx:///
My question is, how can I can I access the file at the first URI with the ms-appx:/// prefix?
Right now the code fails at this line:
ArcGISTiledLayer tpkLayer = new ArcGISTiledLayer(tpkFileUri);
Because it says the URI is not correct, so the reference to tpkLayer is null.
Copy it to your ApplicationData.Current and use ms-appdata:/// would that work for you? ms-appx:/// reference to the files in your appx which is readonly.
here you can read more about the ms-appdata schema: https://blogs.windows.com/buildingapps/2014/06/19/common-questions-and-answers-about-files-and-app-data-part-1-app-data/#j4m8ylp93K7ujk6Q.97
I have an strange problem I have an app that scan a directory and gets a list of files. it processes each file by reading it and doing some stuff. it works fine in the development computer but when I deploy it to the client it gives me the error. Here is the code
public void ProcessIMFiles()
{
DirectoryInfo di = new DirectoryInfo(Globals.ITMDIR);
FileInfo[] Files = di.GetFiles("*.txt");
foreach(FileInfo file in Files)
{
try
{
processThisIMFile(file.FullName);
movefile(file.FullName);
}
catch (Exception ex)
{
MessageBox.Show("error : " + ex.Message);
}
}
}
The error happens in the call to processThisIMFile(file.FullName) see below.
Globals.ITMDIR is a valid path.
private void processThisIMFile(string FileName)
{
string[] Fields = null;
setconnection();
DataTable dt = null;
try
{
string[] Lines = System.IO.File.ReadAllLines(FileName);
foreach (string line in Lines)
{
Fields = line.Split(Globals.delimiter);
if (Fields.Length == 7)
{
//stuff happens here
}
}//Try
catch (Exception e)
{
if (Interactive)
{
MessageBox.Show("Error in the Path: ->" + FileName);
writeToLog(true, "error opening file " + FileName);
}
}
}//end of processThisItemFile
the error happens in the "string[] Lines = System.IO.File.ReadAllLines(FileName)"
line. FileName comes from the di.GetFiles("*.txt"); when I show the actual path it looks ok to me. I have tried with UNC paths and with drive letters path as in C:\tmp\filename.txt or \\server\tmp\filename.txt both fail in the deplopyment machine with "The given path's is not supported" but it works fine in the development machine.
What is going on?
I'm wondering if this could be related to file.fullname somehow altering the file path string and giving an unacceptable result. Can you troubleshoot by using processThisIMFile(Path.GetFullPath(file))? Also, use messagebox.show(file.FullName) prior to processthisimfile to confirm that the result is as expected.
The below code an attempt to try and get get an Mp3 file from the MusicLibrary
It gives me,
A first chance exception of type
'System.UnauthorizedAccessException'
occurred in AccessingPictures.exe
This is my code:
public async void getFile()
{
StorageFolder folder = KnownFolders.MusicLibrary;
try
{
sampleFile = await folder.GetFileAsync("Test1.mp3");
}
catch (FileNotFoundException e)
{
// If file doesn't exist, indicate users to use scenario 1
Debug.WriteLine(e);
}
}
private void btnRead_Click(object sender, RoutedEventArgs e)
{
getFile();
}
Wouldn't we able to access the media files?
I am able to do this using the file picker.
But it does not work while i try to access it directly.
Am i missing anything here ?
To retrieve Pictures from Camera Roll
Void GetCameraPhotos()
{
using (var library = new MediaLibrary())
{
PictureAlbumCollection allAlbums = library.RootPictureAlbum.Albums;
PictureAlbum cameraRoll = allAlbums.Where(album => album.Name == "Camera Roll").FirstOrDefault();
var CameraRollPictures = cameraRoll.Pictures
}
}
You cannot access the files unless it is in response to a user request. i.e. the user must tap a button or something and that tap logic ends up calling your code that accesses the file. If you want to get at the file afterwards, you'll need to copy it in the app's data folder.
I finally figured the issue. It was because i hadn't enabled the capabilities in the Manifest file.
It works like a charm now.
Thanks everyone.
I'm trying to set background image on lock screen in my WinRT app. But when this code is being executed i get an UnauthorizedAccessException with message:
"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
The code was taken from MSDN and looks like OK.
private async void ButtonBase_OnClick(object sender, RoutedEventArgs e)
{
var imagePicker = new FileOpenPicker
{
ViewMode = PickerViewMode.Thumbnail,
SuggestedStartLocation = PickerLocationId.PicturesLibrary,
FileTypeFilter = { ".jpg", ".jpeg", ".png", ".bmp" },
};
var imageFile = await imagePicker.PickSingleFileAsync();
if (imageFile != null)
{
await LockScreen.SetImageFileAsync(imageFile);
}
}
The exception described below is thrown in this line of code:
await LockScreen.SetImageFileAsync(imageFile);
By the way, i've tried to install some applications which can change your background on lock screen, but all of them show error or just crash. Maybe something is wrong with my OS version?
Does anyone know how to solve this problem? Please help!
You need access to the Pictures Library.
Set it by opening your Package.appxmanifest, goto Capabilities and check Pictures Library.
I faced with exactly the same problem. The problem was that my OS wasn't activated. Check this thing on your computer's properties. Hope it helps.
I guess Its some kind of privilege problem may be admin .
Try a work around by applying this code
private async void Button_Click(object sender, RoutedEventArgs e)
{
var client = new HttpClient();
var bytes = await client.GetByteArrayAsync(new Uri("http://transfer-talk.com/wp-content/uploads/Kaka-Real-Madrid.jpg"));
StorageFile sf = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("test.jpg", CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(sf, bytes);
//var imageFile = await imagePicker.PickSingleFileAsync();
//if (imageFile != null)
{
await LockScreen.SetImageFileAsync(sf);
}
}
it will download an Image and set . Not giving an exception in my case neither your code nor mine.
download this sample and try running and see if error exist lock screen sample
also try setting the stream rather using storage file.
await LockScreen.SetImageStreamAsync(await sf.OpenReadAsync());
try and let me know :)