I've been writing a Windows 8 Store App using XAML and C# and the target device is a Windows Surface tablet.
Within my application I use a SQLite database.
To create/load the database I use the following code:
DBPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "MyDatabase.sqlite");
However I'd like to store the database in the Documents folder so I tried the follow line of code to replace my line above :
DBPath = Path.Combine(Windows.Storage.KnownFolders.DocumentsLibrary.Path, "MyDatabase.sqlite");
When I try this I get the following error:
WinRT information: Access to the specified location (DocumentsLibrary) requires a capability to be declared in the manifest.
So I open Package.appxmanifest and select Documents Library under capabilities and under the declarations tab I've added a File Type Association. Then under Properties I've entered
sqlite in the Name box and .sqlite in the File type box. I've entered no other information on the Package.appxmanifest screen.
Now when I run the app I receive the following error:
Could not open database file: MyDatabase.sqlite (CannotOpen)
When I inspect Windows.Storage.KnownFolders.DocumentsLibrary.Path it equals "". I would have expected the full location path here.
Can anyone help and has anybody ever saved a SQLite database to the documents folder?
Thanks in advance.
KnownFolders.DocumentsLibrary does not have a path since it's a virtual location. Take a look at this answer for more details. This could make it impossible to open a SQLite database there, at least using the APIs available in sqlite-net library.
Also before using access to Documents library in your Windows Store app keep in mind that for publishing an app with this capability to the store you need to have a company account. With an individual account such applications will be rejected.
Related
I´m developing an app that is reading jpeg and pdf files from a configurable location on the filesystem.
Currently there is a running version implemented in WPF and now I´m trying to move to the new Windows Universal apps.
The following code works fine with WPF:
public IList<string> GetFilesByNumber(string path, string number)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentNullException(nameof(path));
if (string.IsNullOrWhiteSpace(number))
throw new ArgumentNullException(nameof(number));
if (!Directory.Exists(path))
throw new DirectoryNotFoundException(path);
var files = Directory.GetFiles(path, "*" + number + "*",
SearchOption.AllDirectories);
if (files == null || files.Length == 0)
return null;
return files;
}
With using Universal Apps I ran into some problems:
Directory.Exists is not available
How can I read from directories outside of my app storage?
To read from an other directory outside the app storage I tried the following:
StorageFolder folder = StorageFolder.GetFolderFromPathAsync("D:\\texts\\");
var fileTypeFilter = new string[] { ".pdf", ".jpg" };
QueryOptions queryOptions = new QueryOptions(CommonFileQuery.OrderBySearchRank, fileTypeFilter);
queryOptions.UserSearchFilter = "142";
StorageFileQueryResult queryResult = folder.CreateFileQueryWithOptions(queryOptions);
IReadOnlyList<StorageFile> files = queryResult.GetFilesAsync().GetResults();
The thing is: It isn´t working, but I get an exception:
An exception of type 'System.UnauthorizedAccessException' occurred in TextManager.Universal.DataAccess.dll but was not handled in user code
Additional information: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
I know that you have to configure some permissions in the manifest, but I can´t find one suitable for filesystem IO operations...
Did someone also have such problems/a possible solution?
Solution:
From the solutions that #Rico Suter gave me, I chosed the FutureAccessList in combination with the FolderPicker. It is also possible to access the entry with the Token after the program was restarted.
I can also recommend you the UX Guidlines and this Github sample.
Thank you very much!
In UWP apps, you can only access the following files and folders:
Directories which are declared in the manifest file (e.g. Documents, Pictures, Videos folder)
Directories and files which the user manually selected with the FileOpenPicker or FolderPicker
Files from the FutureAccessList or MostRecentlyUsedList
Files which are opened with a file extension association or via sharing
If you need access to all files in D:\, the user must manually pick the D:\ drive using the FolderPicker, then you have access to everything in this drive...
UPDATE:
Windows 10 build 17134 (2018 April Update, version 1803) added additional file system access capabilities for UWP apps:
Any UWP app (either a regular windowed app or a console app) that declares an AppExecutionAlias is now granted implicit access to the files and folders in the current working directory and downward, when it’s activated from a command line. The current working directory is from whatever file-system location the user chooses to execute your AppExecutionAlias.
The new broadFileSystemAccess capability grants apps the same access to the file system as the user who is currently running the app without file-picker style prompts. This access can be set in the manifest in the following manner:
xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
...
IgnorableNamespaces="uap mp uap5 rescap">
...
<Capabilities>
<rescap:Capability Name="broadFileSystemAccess" />
</Capabilities>
These changes and their intention are discussed at length in the MSDN Magazine article titled Universal Windows Platform - Closing UWP-Win32 Gaps. The articles notes the following:
If you declare any restricted capability, this triggers additional
scrutiny at the time you submit your package to the Store for
publication. ... You don’t need an AppExecutionAlias if you have this
capability. Because this is such a powerful feature, Microsoft will
grant the capability only if the app developer provides compelling
reasons for the request, a description of how this will be used, and
an explanation of how this benefits the user.
further:
If you declare the broadFileSystemAccess capability, you don’t need to
declare any of the more narrowly scoped file-system capabilities
(Documents, Pictures or Videos); indeed, an app must not declare both
broadFileSystemAccess and any of the other three file-system
capabilities.
finally:
Even after the app has been granted the capability, there’s also a
runtime check, because this constitutes a privacy concern for the
user. Just like other privacy issues, the app will trigger a
user-consent prompt on first use. If the user chooses to deny
permission, the app must be resilient to this.
The accepted answer is no longer complete. It is now possible to declare broadFileSystemAccess in the app manifest to arbitrarily read the file system.
The File Access Permissions page has details.
Note that the user can still revoke this permission via the settings app.
You can do it from UI in VS 2017.
Click on manifest file -> Capabilities -> Check photo library or whatever stuff you want.
According to MSDN doc : "The file picker allows an app to access files and folders, to attach files and folders, to open a file, and to save a file."
https://msdn.microsoft.com/en-us/library/windows/apps/hh465182.aspx
You can read a file using the filepicker through a standard user interface.
Regards
this is not true:
Files which are opened with a file extension association or via sharing
try it, by opening files from mail (outlook) or from the desktop...
it simply does not work
you first have to grant the rights by the file picker.
so this ist sh...
This is a restricted capability. Access is configurable in Settings > Privacy > File system. and enable acces for your app. Because users can grant or deny the permission any time in Settings, you should ensure that your app is resilient to those changes. If you find that your app does not have access, you may choose to prompt the user to change the setting by providing a link to the Windows 10 file system access and privacy article. Note that the user must close the app, toggle the setting, and restart the app. If they toggle the setting while the app is running, the platform will suspend your app so that you can save the state, then forcibly terminate the app in order to apply the new setting. In the April 2018 update, the default for the permission is On. In the October 2018 update, the default is Off.
More info
I have a problem with starting the Excel Application under a particular user.
I try to schedule this script (C#) through an application X (not Windows Task Scheduler. And this application will always use a service account to run services on the server). If I run the C# script in command prompt under the same user, it runs. Under the application X, which uses the exact same user, to initiate the C# script, it fails to open the Excel application (not sufficient permission?).
This script calls:
app.Workbooks.Open(ExcelFileName,0,false,Type.missing....), yet it gives the following error:
Microsoft Excel cannot access the file "...". There are several possible reasons:
-The file name or path does not exist.
-The file is being used by another program.
-The workbook you are trying to save has the same name as a currently open workbook.
I tried all the methods that I found online to no avail.
Create directory “C:\Windows\SysWOW64\config\systemprofile\Desktop” (for 64 bit Windows) or “C:\Windows\System32\config\systemprofile\Desktop” (for 32 bit Windows). Then Set full control permissions on Desktop directory above (for example in Win7 & IIS 7 & DefaultAppPool set permissions for user “IIS AppPool\DefaultAppPool”)
Changed the DCOM config for the Microsoft Excel application to include this user for Local/Remote Launch and Access
Enabled all macros in Excel and set the Trust Center.
Add the user to have full control on all folders that contain the Excel file.
Under DCOM config, Microsoft Excel Application, if I modify the Identity tab to check on "This User" and enter the username/password to let Excel always run under that user. Then the application runs perfectly. However, other users can't run the excel application on their own with the following error: "Cannot use object linking and embedding". If I check "Use the launching user", then Excel can't be launched. No errors in the logs or events anywhere to check.
Yet, still the same error. I think it's permission but I am not sure where and what to do for this to work.
Now, normally, when I run this excel report, I can double-click on the file and it'd automatically run, save the new parameters into the current file and generate a new excel file (with date attached to the file name). That means there is a change (save) to the original file.
I appreciate all your help!
I found the problem is the layer of security in the server!
Creating the Desktop folder inside the C:\Windows\System32\config\systemprofile and giving the service account permission to access the desktop folder is not enough.
I modified the C:\Windows\System32\config (or C:\windows\SysWOW64\config) folder to allow permission to the service account in security tab.
Then I also had to set up the same permission for the sub folder C:\Windows\System32\config\systemprofile (or C:\windows\SysWOW64\config\systemprofile) for the service account.
This works!
Microsoft Excel cannot access the file in Server 2012 Excel 2016.. checked various solutions online to create folder desktop in C:\Windows\SysWOW64\config\systemprofile\desktop.. didn't work for this but then i added a folder desktop in System32 and that definitely worked.
Since I have 64-bit Excel installed, the proper directory turned out to be the
c:\windows\system32\config\systemprofile\desktop
I ran across another way you can get this error: when you try to save a file with an "illegal" name, such as one with whacks (forward slashes) in it.
For that reason, it would seem reasonable that the err msg would give that as one possible explanation of the problem, but...no!
Specifically, I was trying to save a file named C:\RoboReporter\ABUELITOS\20160524_1327\ABUELITOS - Fill Rate - 4\1\61910B10
The whacks (shown as backwhacks in the copied exception text, but seen as forwardwhacks when hovering over the value when debugging) were the cause of the discombobulation. Once I fixed that by replacing whacks with underscores:
filename = String.Format("{0}\\{1} - Fill Rate - {2}.xlsx", uniqueFolder, _unit, _begDate.ToShortDateString());
filename = filename.Replace("/", "_");
...all went swimmingly.
I am exporting an excel using c# code and spreadsheetlight dll.
I am trying to insert a picture into excel, everything works well on local machine but on live web site it gives following error
Access to the path 'F:\sitesroot\0\Images\Logo.png' is denied
My c# code.
string filePath = Server.MapPath("~/Images/Logo.png");
SLPicture pic = new SLPicture(filePath); //SLPicture - An inbuilt class for inserting image
Currently what I am doing is manually providing access rights on IIS server but which is not the correct way to go since each time I upload the service I have to redo that again and again
Any expert advice - How I can provide access right through code?
Or How to get rid of this error.
Thanks.
Assuming you are using Cloud services...
You are supposed to use Local Storage for this (http://msdn.microsoft.com/en-us/library/windowsazure/ee758708.aspx).
Basically;
In your Cloud project, go to the properties for the Role and select Local Storage.
Add a new local storage and give it a name, i.e. "foo" and a maximum size. If this is for temporary processing rather than caching, you probably want to tick "Clean on role recycle".
In your code call RoleEnvironment.GetLocalResource("foo") to get the folder name you can use and then do something like Path.Combine("path","Logo.png") to get a file name which you can then write to.
I have the code to save a file in a folder in directory
string timestamp = DateTime.Now.ToString("MM-dd-yyyy.HH-mm-ss");
var file = File.Create("Owe-Data.txt" + timestamp);
var com = System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase + timestamp + #"\Data" + file;
MessageBox.Show(com);
if (!Directory.Exists(com))
{
Directory.CreateDirectory(com);
}
using (var sw = new StreamWriter(com))
{
sw.WriteLine(InputData);
}
}
i Displayed COM it gives path bt i cant see the Data folder or Owe-Data file at that path
Anybody can tell why this happening, or should i save the Data folder in current directory where this prgram running? bt i dnt know how to reach that path. Any solutions ??
Working on windows phone 5, visual studio 2008 .NET framwork 2.0
As per the Exceptions section of documentation,the above exception is thrown when
ArgumentException ------- folder is not a member of System.Environment.SpecialFolder.
It means the OS where you are running this command does not have Environment.SpecialFolder.CommonApplicationData as one of the special folder.
For knowledge,
Environment.SpecialFolder.ApplicationData is the most common one. This folder holds per-user, non-temporary application-specific data, other than user documents. A common example would be a settings or configuration file.
Environment.SpecialFolder.CommonApplicationData is similar, but shared across users. You could use this to store document templates, for instance.
Environment.SpecialFolder.LocalApplicationData is a non-roaming alternative for ApplicationData. As such, you'd never store important data there. However, because it's non-roaming it is a good location for temporary files, caches, etcetera. It's typically on a local disk.
I think the problem may be that Environment.SpecialFolder.CommonApplicationData is common and shared between different users and the user with which you have logged in is not having rights to access the folder or the Visual Studio has not been started in Admin mode.
EDIT Look at link and try to add a manual registry Common AppData defined in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\
Given you are asking about a .NET Windows Phone application as per the tags
I think your problem is that a .NET Windows Phone application does not have direct access to the file system; it can only access IsolatedStorage this is by design.
I would quote a Microsoft source for this but I can't seem to find one!
EDIT
See this article from MSDN
I am trying to using the ESENT windows database with the managedesent library but I always get the error
Error FileAccessDenied (JET_errFileAccessDenied, Cannot access file, the file is locked or in use)
The code to open the database is
m_Dictionary = new PersistentDictionary<string, PropertyStruct>("BaseEstateCachedPropertySummary2");
I am testing this on Windows 7 and the application is an ASP.NET application. Does anyone have any ideas about this, documentation is pretty slim.
Are you trying to open an existing database used by another service (e.g. the Windows Update database)? Esent databases are single-process only so you have to stop any other processes that are using the same database.
I found an answer. Apparently I didn't have write permissions to the default directory where it puts the database so I had to specify the full path such as.
m_Dictionary = new PersistentDictionary<string, PropertyStruct>(#"c:\Data\BaseEstateCachedPropertySummary2");