Windows Phone 8 UnauthorizedAccessException when opening file - c#

I am having a very strange error when trying to access a ".stl" file in the "Stl" folder of my application when the app is downloaded from the Windows Phone Marketplace. It does not exhibit this behavior when it is launched from Visual Studio 2012 Express in either debug or release mode. Once I try loading a file it gives me an "System.UnauthorizedAccessException Access to path 'C:\Data\Programs\APPUID\Install\Stl\test.stl' is denied" exception while accessing a ".gcode" file in an almost exactly the same fashion from the "GCode" causes no error what so ever.
I have no idea what could be causing this or how to debug this because I don't know if I can somehow attach the debugger to an instance of the store downloaded app.
I also have no idea what could possibly be different between deploying the exact same app from the store and from Visual Studio. The Visual Studio installed app also does not give any troubles if the app is launched from the phone without the debugger being attached.
Any ideas?
PS. The file is being opened by a filestream which is then used by a binarreader. I am not sure if the source code is really needed and for which part but the important line is just:
FileStream fileStream = new FileStream(filePath, FileMode.Open);
Where "filePath" in this case is "Stl\test.stl".

Without seeing your actual code it is hard to say what the problem is. So instead of attempting to read your mind I will offer an alternative solution.
I have worked extensively with Isolated Storage on the Windows Phone and I have learned this.
There is no library, no API, no SDK, no Web service, in the world, that has worse error reporting than the Isolated Storage on windows phone.
EVERYTHING is Invalid Access or Unauthorized Access with ZERO further information.
To remedy this I created a DLL that serializes objects to the Isolated Storage for you.
All you have to do is put [DataContractAttribute] above your class name and [DataMemeber] above any variable you want saved. Then you just pass your object and unique name into the savefile method. That's it! Instant save
You can find my free DLL EZ_Iso.dll for download here. With example code and instructions
The code is open source so if you wish you may also decompile the dll and see how it all works.
Feel free to reach out to me here or on twitter if you have any questions or enhancements.

Ok I figured it out. The "install" directory is actually restricted access but for some reason the Visual Studio signing process leaves the app with enough permissions to access this folder. The correct procedure of determining a relative directory is not to use "Directory.GetCurrentDirectory()" but rather to use "ApplicationData.Current.LocalFolder". Hope this helps!

Related

New C# project cannot open ACCDB microsoft database file

I recently had a new project assigned to me (I'm new to C# and I'm a junior). It makes use of a Microsoft access database file (.accdb file)
I've imported the project into Visual Studio but I can't for the life of me run the code. Initially I had file register issues, and I think I managed to resolve that by getting the IT teams to install a "2007 Office System Driver: Data Connectivity Components" driver from the Microsoft website.
Bow the error says:
System.Data.OleDb.OleDbExceptions: 'Cannot open database''. It may not be a database that your application recognizes, or the file may be corrupt.'
The team I'm trying to help only has one dev (working from a different country) who is the main person to handle the code. It works on her side, but she doesn't really have the experience to help me troubleshoot this.
I tried sending her my database file, for her to swap her file for mine, and she said it was still working, so it sounds like the issue might not be to do with the file?
Could I get any help if possible? So far my only approach is to keep googling the error.
But the only resolutions I see are from people who have database files nearing their file size limit (2GB). My database file is just 1MB.
The database file is password protected (the password happens to be in the code). I opened the database file (Microsoft access opens) and entered the password and I had no issue accessing the data)
Out of luck, I managed to find the right article to help me!
The issue with Microsoft access database files is only one user can really use then at a time I believe.
I saw a forum about potential locks made by other users. I googled how to remove locks but it seems that it might not be a lock issue (Microsoft creates a lock file which I dont have).
Regardless, I assumed that the issue is still somewhat similar. Since I had access to the database in Microsoft Access, I decided to open a new database, then go to external data tab and click on access to import EVERYTHING from the other file. Then I just renamed to old file and give my new file the original name.
I reran the code and it worked!
I dont know why the other dev had no issue opening the file. My assumption is that because she is the only developer her laptop is already 'set up' in some way to run everything as normal, whereas if someone new tried (or if something happens and she has to re-open the code on a new laptop) they would have to try and replicate the 'set up' or try and work from scratch
Hope this helps

What's the default file path in WinRT/WP 8.1?

Hello fellow programmers.
I recently made a mistake while using the SQLite-NET package for Windows Phone 8.1. When opening a new SQLiteConnection, I would give as parameter to its constructor the string "data.db", without being actually aware of what was going on under the hood. Later on, I noticed that the file wouldn't be deleted, even if I uninstalled the application (since I would have in my app the same entries that I had before uninstalling it); I assume that I should be using the local folder for application data instead.
However, here is the real question: what the hell is the folder where the data.db file was created? I tried to figure it out with the following piece of code:
var file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///data.db"));
System.Diagnostics.Debug.WriteLine(file.Path);
and what I got as output of the WriteLine method was the path
C:\Data\SharedData\PhoneTools\AppxLayouts\f7529f24-ba24-4fdb-8353-cff9214180a0VS.Debug_ARM.Valbrand\data.db,
which only got me even more confused. I couldn't find any satisfactory info on this, and I would REALLY like to further my understanding of what happened here.
Thanks in advance!
The path you are looking at is the install directory of your app. You have a Silverlight 8.1 app, so the path is slightly different than a Silverlight 8.0 app, but the articles here and here will help you get a rough understanding.
The recommended usage of this directory is to take the resources that you want backed up out of it on first run and move them to the app data container, so they can be backed up by the system.
C:\Data\SharedData\PhoneTools\AppxLayouts\f7529f24-ba24-4fdb-8353-cff9214180a0VS.Debug_ARM.Valbrand\data.db
This is the path on your phone/emulator.
And This is not the location where you can find in your PC.

Windows Form Application : Publish issue

I'm very new to Visual Studio 2010. I decided to create a simple WFA with C#.
Everything work fine with Images and Audio playback. My intention is to create a standalone application and send it to my friend as a gift. Problem I facing now is that when I tried to publish the application, the Images / Audio is still using the same location in my PC. So it won't play nor display any images.
Any comment on this or guide for me? I did try search for solution but doesn't seems to have any luck.
This is the code that I used to play Audio :
SoundPlayer ply = new SoundPlayer(#"C:\Users\Liam619\Documents\Visual Studio 2010\Projects\BirthdayApp\BirthdayApp\Resources\BirthdaySong.wav");
If I remove or change the path, the Application will hit error for locating the Audio file.
There may be several solutions to your problem.
a) embed the sound into a resource. As a beginner, resources may be a bit tricky to get it right the first time. But I want to encourage you reading something about it. You'll need resources when you want to translate your first program.
b) create an installer which copies the sound file to the installation directory. Try InnoSetup. If you're a programmer, sooner or later, you'll need to create a Setup anyway. Always worth knowing how to do that.
In that case, you still need the path to the sound file, but if you install your EXE into the same path as the sound file, see getting the application's executable directory.
everything in the database whether images or audio refers to your own server database.you have to send the database too with the app and the correct version .NET framework needs to be installed on the target PC.

windows phone 8, applicationsettings not persisted

I have the following strange behaviour in my Windows phone 8, C# App.
I am saving a Setting with:
private void SaveProperty<T>(T property, string propertyName)
{
if (IsolatedStorageSettings.ApplicationSettings.Contains(propertyName))
IsolatedStorageSettings.ApplicationSettings[propertyName] = property;
else
IsolatedStorageSettings.ApplicationSettings.Add(propertyName, property);
IsolatedStorageSettings.ApplicationSettings.Save();
}
When the app runs, I can read all settings I stored in IsolatedStorageSettings.ApplicationSettings.
But when I re-open my app (open it from the app list), the IsolatedStorageSettings.ApplicationSettings-Dictionary contains Zero (0) Keys and Values.
Am I missing something?
I used the ISETool.exe to take snapshots of the IsolatedStorage of my app (thanks to chepene).
I saw this behaviour: when I wrote the Settings (that means after the SaveProperty<T>() function finished), and the app is still running, I have the Settings saved in _ApplicationSettings. This agrees with my Observation that I can read from the IsolatedStorageSettings.ApplicationSettings when the app is running.
The _ApplicationSettings-file also exists when the is tombstoned or not running (when I can Access it by Holding the back-button of the phone and when the app is closed with the back-button).
But when the app is opened again (via the app list), the _ApplicationSettings-file is gone...
I also see that, when I'm writing a file into the IsolatedStorage with:
SharedStorageAccessManager.CopySharedFileAsync(
Windows.Storage.ApplicationData.Current.LocalFolder, fileName+"orig",
Windows.Storage.NameCollisionOption.ReplaceExisting, fileID);
and when I then don't read this file, it is gone when I open the app the next time.
By the way, to avoid confusion: I am not reinstalling the app each time I open it.
If you need more Information please ask.
Any help appreciated.
With AppSettings, I've seen something similar on WP7/7.5, but it happened only when my property-value's type was a class that was not known to the serializer.
Are you sure that there were no exceptions:
during Save
during App Exit (since the App may dump the settings at that point)
during the time that App loads the settings for the first time after launch?
Note that this doesn't necessarily must mean the app crashing. I mean, any exceptions, those internally silenced or user-handled too. Please check the VisualStudio's Output panel for "first chance exceptions" log. If any I/O or security or serialization exception shows up, then investigate there. If i remember well, there's even a whole set of isolated-storage exceptions that are easily interceptable from debug/exceptions menu.
However, the issues I had with unknown or nonserializable types does not explain at all why your extra non-appsettings files would evaporate.
Another thought: maybe some additional tool performs something like 'clean deploy' for you? I don't remember exactly, but I think that VisualStudio's deployment cycle was quite plain:
rebuild
remove/uninstall old app from device -- so probably purges isolatedstorage
install new app onto device
So, maybe that's the cause? Hm.. on afterthought and re-reading your question again, you've said about running the app from the applist, so that rather is not the case. Be sure to check firstchance exceptions then!
Thanks to quetzalcoatl I found the solution:
I am storing all my files in the root Folder of my app. At the start I am then reading all my files (via a DataContractSerializer) and casting it to my model. Since it happens sometimes that my files get corrupt, I delete every file which throws a SerialzationException. But as I read every file, and since _ApplicationSettings is not castable to my model, I am deleting _ApplicationSettings automatically.... So I learned that the ApplicationSettings are,just a file in the root folder, which I am allowed to read and delete. So the quintessence is to never write into the root Folder.

Access to the path denied error in C#

I have read a similar post, but i just cant figure out the problem.
I have changed the windows permissions and changed routes.
When i try to save a file it throws me the exception:
Access to the path **** denied.
string route="D:\\";
FileStream fs = new FileStream(route, FileMode.Create); <--here is the problem
StreamWriter write = new StreamWriter(fs);
patient person = new patient();
patient.name = textBox1.Text;
patient.name2 = textBox2.Text;
You are trying to create a FileStream object for a directory (folder). Specify a file name (e.g. #"D:\test.txt") and the error will go away.
By the way, I would suggest that you use the StreamWriter constructor that takes an Encoding as its second parameter, because otherwise you might be in for an unpleasant surprise when trying to read the saved file later (using StreamReader).
Did you try specifing some file name?
eg:
string route="D:\\somefilename.txt";
tl;dr version: Make sure you are not trying to open a file marked in the file system as Read-Only in Read/Write mode.
I have come across this error in my travels trying to read in an XML file.
I have found that in some circumstances (detailed below) this error would be generated for a file even though the path and file name are correct.
File details:
The path and file name are valid, the file exists
Both the service account and the logged in user have Full Control permissions to the file and the full path
The file is marked as Read-Only
It is running on Windows Server 2008 R2
The path to the file was using local drive letters, not UNC path
When trying to read the file programmatically, the following behavior was observed while running the exact same code:
When running as the logged in user, the file is read with no error
When running as the service account, trying to read the file generates the Access Is Denied error with no details
In order to fix this, I had to change the method call from the default (Opening as RW) to opening the file as RO. Once I made that one change, it stopped throwing an error.
I had this issue for longer than I would like to admit.
I simply just needed to run VS as an administrator, rookie mistake on my part...
Hope this helps someone <3
If your problem persist with all those answers, try to change the file attribute to:
File.SetAttributes(yourfile, FileAttributes.Normal);
You do not have permissions to access the file.
Please be sure whether you can access the file in that drive.
string route= #"E:\Sample.text";
FileStream fs = new FileStream(route, FileMode.Create);
You have to provide the file name to create.
Please try this, now you can create.
TLDR : On my end, it had something to do with AVAST ! => Whitelist your application.
All of a sudden, I also got this UnauthorizedAccessException problem in the windows WPF program I'm writing. None of the solutions worked - except I couldn't figure out how to elevate my application to full privileges (not using VS) while at the same time, being already on the administrator account, I didn't feel the need to dig that deep in permission concerns.
The files are image files (jpg, psd, webp, etc.) I wasn't trying to open/write a directory, it has always been a valid path to a file, and I needed to write to the file, FileAccess.ReadWrite was inevitable. The files (and any of their parent directory) were not readonly (I even checked by code prior calling new FileStream(path, mode, access, share) via FileInfo.IsReadOnly) - so what happenned all of a sudden ???
Thinking about : I had an had drive crash, so I unpacked a backup of my solution code from another drive. In the meantime, I added codes in my application to PInvoke APIs to directly read hard drive sectors physical bytes as well as USB plug/unplug monitoring.
I started to get the Exception when I added those, but even though I temporarly removed the related codes from the application, I still got the UnauthorizedAccessException.
Then I remembered one thing I've done long ago, a painstaking similar issue where I wanted my application to communicate sensible data via Wifi, which was to add the executable among AVAST exceptions, and the assembly directory aswell (My app was already among the authorized apps through firewall)
Just did it for my application in AVAST settings, AND THE EXCEPTION IS GONE !!! Two whole days I'm lurking StackOverflow and the web to get moving on, FINALLY !
Details : I can't pinpoint exactly what AVAST didn't like in my application as the only changes I made :
Retrieved then launched the backup code - it worked like a charm, files (images) opens/write without problems (3 days ago)
Added USB detection (3 days ago - Just tested the code, didn't tried to open an image)
Added PInvoke physical drive direct read (2 days ago - FileStream, and the logic to define where/how to scan the damaged drive - Just tested the code, didn't tried to open an image)
Added image format detection starting from Jpg/Jfif.. 2 days ago, got the exception upon testing the code.
While searching for solutions, added an Image Gallery WPF UserControl to diplay pictures based on their signature and check which files gives the exception : almost all of them (some files opens/write okay - why ???)
Tried everything I've found on SO (since the last 2 days) until I opened AVAST settings and whitelist my application.
... now I can move on into adding a bunch of file signatures to retrieve as many datas as I could.
If this may help those who like me, aren't failing on the "I'm passing a directory path instead that of a file", yet, have no time to learn exactly why antiviruses think our own code is a malware.
Just Using the below worked for me on OSX.
var path = "TempForTest";

Categories