I am using SQLite-net nuget package in my UWP application. I want to create a local database file to use as such:
var s = new SQLiteConnection("myDbSQLite.db3", SQLiteOpenFlags.Create);
But it throws the error:
Could not open database file:
C:\Path\MyProject\bin\x86\Debug\AppX\myDbSQLite.db3 (Misuse)
I see in other posts they suggest to use SQLiteConnection.CreateFile("MyDatabase.sqlite"); but I don't see that method?
EDIT
The code
FileStream fs = File.Create(path);
Throws the exception:
UnauthorizedAccessException access to the path is denied
So I think this is a permission issue I am having with UWP. Is there something in the capabilities that I need to set?
Check your permissions on the folder, and also try using this for the constructor
_database = new SQLiteAsyncConnection(
"myDbSQLite.db3",
SQLiteOpenFlags.Create |
SQLiteOpenFlags.FullMutex |
SQLiteOpenFlags.ReadWrite );
Because creating a file in UWP must be done with the UWP API, if you're going to use this nuget library, you have to accommodate by creating it yourself first:
// Create the empty file; replace if exists.
Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
storageFolder.CreateFileAsync("myDbSQLite.db3", Windows.Storage.CreationCollisionOption.ReplaceExisting);
My UWP app is actually part of a Xamarin.Forms app that is using shared code, so if your app is solely UWP there's probably a better library, such as this one that Codexer referred.
You should use a folder wher you have write-access to. So please try the following code:
String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string dbFile = Path.Combine( path, "myDbSQLite.db3");
var s = new SQLiteConnection( dbFile, SQLiteOpenFlags.Create);
This worked for me:
var databasePath = Path.Combine(GetLocalFileDirectory(), "MyData.db");
try
{
// Create the empty file; replace if exists.
db = new SQLiteAsyncConnection(databasePath,
SQLiteOpenFlags.Create |
SQLiteOpenFlags.FullMutex |
SQLiteOpenFlags.ReadWrite);
}
catch(Exception ex)
{
throw new Exception(ex.Message);
}
public string GetLocalFileDirectory()
{
var docFolder = FileSystem.AppDataDirectory
var libFolder = Path.Combine(docFolder, "Databases");
if (!Directory.Exists(libFolder))
{
Directory.CreateDirectory(libFolder);
}
return libFolder;
}
Related
I'm trying to get all the videos in a specific folder inside the Videos library using UWP, right now I can get all videos inside the Videos library, but I'd like to reduce my results to only those inside the specified folder. My code is this:
Windows.Storage.Search.QueryOptions queryOption = new QueryOptions(CommonFileQuery.OrderByTitle, new string[] {".mp4"});
queryOption.FolderDepth = FolderDepth.Deep;
var files = await KnownFolders.VideosLibrary.CreateFileQueryWithOptions(queryOption).GetFilesAsync();
StorageFile videoToPlay = (files[new Random().Next(0, files.Count)] as StorageFile);
var stream = await videoToPlay.OpenAsync(Windows.Storage.FileAccessMode.Read);
Player.SetSource(stream, videoToPlay.ContentType);
Debug.WriteLine(Player.Source);
How could I access a subfolder named "Videos to Play" and then get all the videos inside that folder? I tried accesing it by using a path like:
string localfolder = Windows.Storage.ApplicationData.Current.LocalFolder.Path;
var array = localfolder.Split('\\');
var username = array[2];
string[] allVideos = System.IO.Directory.GetFiles("C:/Users/" + username + "/Videos/Videos to Play");
But I get access denied even though I already requested access to the Videos library (and the fact that the first example works shows that I actually have access to it).
try
{
var folder = await KnownFolders.VideosLibrary.GetFolderAsync("Videos to Play");
}
catch (FileNotFoundException exc)
{
// TODO: Handle the case when the folder wasn't found on the user's machine.
}
In the folder variable you'll have the reference to the desired folder. Then it's the very same stuff that you already do, but instead of KnownFolders.VideosLibrary folder use this one!
I am trying to overwrite the database in my local folder with one that is in my pictures directory I use the following
StorageFolder storageFolder = KnownFolders.PicturesLibrary;
String picName = "SqlLiteWin8-1.db";
var file2 = await storageFolder.TryGetItemAsync(picName) as IStorageFile;
StorageFile fileCopy = await file2.CopyAsync(Windows.Storage.ApplicationData.Current.LocalFolder, "SqlLiteWin8-1.db", Windows.Storage.NameCollisionOption.ReplaceExisting);
It seems to work and the file is copied and overwrite the old one
Problem is when I run the app it still shows the old data
I checked by manually deleting the db in the local state folder of the app then running the code and it copies it to the folder.
I think its still using the database in the app package and not the one in the local folder
The database in the pictures directory is identical to the one stored in the app except 1 record is modified
I want to overwrite it so that I can just supply a new db file to users and the app will use the new data or is there a way of bypassing this and read the DB straight from the pictures directory instead of the local folder
one though was it uses the following code to check if the db exists and copies if it doesnt could this be what is causing it not to work
public static async Task<bool> checkDataBaseConnection()
{
bool isDatabaseExisting = false;
try
{
var uri = new Uri("ms-appx:///SqlLiteWin8-1.db"); //in application folder
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
var destinationFolder = ApplicationData.Current.LocalFolder;//local appdata dir
//await file.DeleteAsync();
// var f = await destinationFolder.GetFileAsync("data.db3");
await file.CopyAsync(destinationFolder);
}
catch (Exception ex)
{
throw ex;
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("AFSMOJO.db");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
return isDatabaseExisting;
}
As always your help is greatly appreciated
Mark
Ignore my stupidity I found what was wrong I was connecting to the internal database instead of the local one
I changed
var db = new SQLiteConnection("SqlLiteWin8-1.db");
to
var db = new SQLiteConnection(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "SqlLiteWin8-1.db"));
and now i can change my db in the picture folder and it copies it to the local one and uses the new data
Thanks
Mark
I am using the following code to checkout a file but it works rarely. It works for a particular file while it doesnt work for some files.
My code is
oSettings.DefaultAcquisitionOption = VDF.Vault.Settings.AcquireFilesSettings.AcquisitionOption.Checkout | VDF.Vault.Settings.AcquireFilesSettings.AcquisitionOption.Download;
oSettings.LocalPath = fldrpathco;
oSettings.AddEntityToAcquire(oFileIteration);
connection.FileManager.AcquireFiles(oSettings);
string p = oSettings.LocalPath.ToString() + oFileIteration.ToString();
My requirement is to download the dwg file in the working folder. Can anyone tell me what may be wrong in the code?
Try this example by Wayne Brill: http://adndevblog.typepad.com/manufacturing/2013/06/use-or-with-defaultacquisitionoption-to-download-checkout-with-acquirefiles.html
Code for reference:
private static void downloadFile (VDF.Vault.Currency.Connections.Connection connection,
VDF.Vault.Currency.Entities.FileIteration file, string folderPath)
{
var settings = new VDF.Vault.Settings.AcquireFilesSettings(connection);
settings.AddEntityToAcquire(file);
settings.DefaultAcquisitionOption = VDF.Vault.Settings.AcquireFilesSettings.AcquisitionOption.Checkout |
VDF.Vault.Settings.AcquireFilesSettings.AcquisitionOption.Download;
settings.LocalPath = new VDF.Currency.FolderPathAbsolute(folderPath);
connection.FileManager.AcquireFiles(settings);
}
I'm programming an app that interact with dropbox by use DropNet API. I want to check if the folder is exist or not on dropbox in order to I will create one and upload file on it after that. Everything seen fine but if my folder is exist it throw exception. Like this:
if (isAccessToken)
{
byte[] bytes = File.ReadAllBytes(fileName);
try
{
string dropboxFolder = "/Public/DropboxManagement/Logs" + folder;
// I want to check if the dropboxFolder is exist here
_client.CreateFolder(dropboxFolder);
var upload = _client.UploadFile(dropboxFolder, fileName, bytes);
}
catch (DropNet.Exceptions.DropboxException ex) {
MessageBox.Show(ex.Response.Content);
}
}
I'm not familiar with dropnet, but looking at the source code, it appears you should be able to do this by using the GetMetaData() method off of your _client object. This method returns a MetaData object.
Example:
//gets contents at requested path
var metaData = _client.GetMetaData("/Public/DropboxManagement/Logs");
//without knowing how this API works, Path may be a full path and therefore need to check for "/Public/DropboxManagement/Logs" + folder
if (metaData.Contents.Any(c => c.Is_Dir && c.Path == folder)
{
//folder exists
}
I have this file: C:\Documents and Settings\extryasam\My Documents\Visual Studio 2010\Projects\FCR\WebApplication4\config\roles.txt and I want to import it into my C# application. If I insert the full path it's ok, but I want to do something similar to what we do with websites, and that is "\config\roles.txt"
However with the below code, this is not working.
This is my code:
public string authenticate()
{
WindowsIdentity curIdentity = WindowsIdentity.GetCurrent();
WindowsPrincipal myPrincipal = new WindowsPrincipal(curIdentity);
//String role = "NT\\Internet Users";
//string filePath = Server.MapPath("config/roles.txt");
//string filePath = (#"~/WebApplication4/config/roles.txt");
//string filePath = Path.GetDirectoryName(#"\config\roles.txt");
string filePath = Path.GetPathRoot(#"/config/roles.txt");
string line;
string role = "";
if (File.Exists(filePath))
{
StreamReader file = null;
try
{
file = new StreamReader(filePath);
while ((line = file.ReadLine()) != null)
{
role = line;
}
}
finally
{
if (file != null)
{
file.Close();
}
}
}
if (!myPrincipal.IsInRole(#role))
{
return "401.aspx";
}
else
{
return "#";
}
}
In ASP.NET, you can use ~/config/roles.txt - in combination with Server.MapPath(), you can get the full path.
[...] ASP.NET includes the Web application root operator (~), which
you can use when specifying a path in server controls. ASP.NET
resolves the ~ operator to the root of the current application. You
can use the ~ operator in conjunction with folders to specify a path
that is based on the current root.
(see http://msdn.microsoft.com/en-us/library/ms178116.aspx)
So you could try the following:
string filePath = System.Web.HttpContext.Current.Server.MapPath("~/config/roles.txt");
You can use Server.MapPath to map the specified relative or virtual path to the corresponding physical directory on the server.
Since you are working locally you can use absolute path to that file and it's will works.
But what about situation when web application that contains roles.txt file will be deployed on some web server and user will try to access this file from another machine?
You can use the approach below to access file hosted on a web server from a Windows application:
using (var stream = new WebClient().OpenRead("your_web_application_root_url/configs/roles.txt"))
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
Be warned that share security settings over network is not quite good idea.
You should select your file and press F4, and choose copy to output directory. Then you will be able to work with it
You could try embedding the file as a resource in your project. Something like this: How to embed a text file in a .NET assembly?