I'm trying to import an excisting SQLitedatabase in my Windows Universal project.I followed along this tutorial. Which does just what I want.
However it states:
then copy the database with a .sqlite extension to the root of the shared project in your universal app.
So I added my excisting databse to the root of my Shared Project
However when I try the following code I get an IOException the File could not be found.
private async Task CopyDatabase()
{
bool isDatabaseExisting = false;
try
{
StorageFile storageFile = await ApplicationData.Current.LocalFolder.GetFileAsync("FixedCamerasOK.sqlite");
isDatabaseExisting = true;
}
catch(Exception ex)
{
isDatabaseExisting = false;
}
if (!isDatabaseExisting)
{
StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync("FixedCamerasOK.sqlite");
await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder);
}
}
So where do I place the .sqlite file so it can be found.
Add the File As Content instead as none or empty
Search for the file(FixedCamerasOk.sqlite) in the Installed folder to see if it exists
public async Task<bool> DoesDatabaseExist()
{
bool dbexists = true;
try
{
var files = Package.Current.InstalledLocation.GetFilesAsync();
var retvalues = (from f in await files
where f.Name == "FixedCamerasOk.sqlite"
select f);
int count = retvalues.Count();
if (count > 0)
return dbexists;
else
return false;
}
catch (Exception)
{
dbexists = false;
}
return dbexists;
}
First select your file and in properties select Build Action as Content then open the file like this
StorageFile file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///FixedCamerasOK.sqlite"));
Related
I've been trying to create a function where the user will download a file(PDF) when a button is clicked.
I stored the file in firebase storage and can be accessible via url/link. I found this solution How to download files in Xamarin.Forms? that helps you download from a url. However I got an error that say **System.UnauthorizedAccessException:** 'Access to the path '/data/user/0/com.companyname.pawadopt_v5/files' is denied.' I already made sure to check and request permission using Xamarin.Essentials but I keep getting this error even with Permission.Granted for StorageRead and StorageWrite.
Here is my code:
Download Function
public async Task<bool> DownloadFile(string fileURL)
{
var checkPermission = await PermissionServices.PermissionClientInstance.checkStorage();
if(checkPermission == true)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
try
{
var client = new HttpClient();
var downloadStream = await client.GetStreamAsync(fileURL);
var fileStream = File.Create(path);
await downloadStream.CopyToAsync(fileStream);
return true;
}
catch (Exception ex)
{
return false;
}
}
else
{
return false;
}
}
Check and Request Permission
var Readpermission = await Permissions.CheckStatusAsync<Permissions.StorageRead>();
var Writepermission = await Permissions.CheckStatusAsync<Permissions.StorageWrite>();
if (Readpermission != PermissionStatus.Granted || Writepermission != PermissionStatus.Granted)
{
Readpermission = await Permissions.RequestAsync<Permissions.StorageRead>();
Writepermission = await Permissions.RequestAsync<Permissions.StorageWrite>();
}
if (Readpermission != PermissionStatus.Granted && Writepermission != PermissionStatus.Granted)
return false;
else
return true;
What are your thoughts and solutions about this?
Any ideas and solution are greatly appreciated
UPDATE
When I changed the path into string localPath = Path.Combine(FileSystem.AppDataDirectory,"File.pdf");, No error shows and prompt the 'Download Successful'. However I cant find where this local path is.
I'm working on an ASP.NET Core 5 project. I have this action method:
public async Task<IActionResult> CreateV3EnterCheckFile(IFormFile MarksFile)
{
var filesCount = Directory.GetFiles("Uploads").Length;
string path = Path.Combine("Uploads", filesCount + 1 + ".xlsx");
await MarksFile.SaveToAsync(path);
var xlImporter = new XLImporter();
var importedData = await xlImporter.ImportSheetAsync(path, 0);
var r = (from x in importedData select new { ID = x[0], StudentId = x[1] }).ToList();
System.IO.File.Delete(path);
return View();
}
I tried to get IFormFile uploaded file by the user to save it on the server and querying it using one of my projects (that uses LinqToExcel library).
I am querying the data and everything is perfect I still have just one problem it is this line of code:
System.IO.File.Delete(path);
It throws an exception and the message is I can't delete that file because it is still being used by another process.
I'm very sure that the process is related to the LinqToExcel library.
More details :
SaveToAsync is an extension method created by me that is its definition
public static Task SaveToAsync(this IFormFile file, string pathToSaveTo)
{
return Task.Factory.StartNew(() =>
{
using (Stream fileStream = File.Open(pathToSaveTo, FileMode.Create, FileAccess.ReadWrite, FileShare.None))
{
file.CopyTo(fileStream);
}
});
}
Please - is there any way or method or solution to delete this file even if it is being used by another process?
Massive thanks in advance.
Based on the source code of ExcelQueryFactory (https://github.com/paulyoder/LinqToExcel/blob/master/src/LinqToExcel/ExcelQueryFactory.cs) I would try the following:
ExcelQueryFactory has a ReadOnly Property. For read only access (if applicable) I would set it to true when creating the instance.
More important: IExcelQueryFactory implements IDisposable, so you can (should) use a using block:
using (var excelFile = new ExcelQueryFactory(pathToExcelFile) {ReadOnly = true})
{
// Do your work.
}
Of course you can use using var ..., but if you need a more reduced scope, the "old" using syntax allows more control.
I assumed that your Uploads folder is under webroot.
You can try this:-
public YourControllerName(IHostingEnvironment he) //input parameter
{
_he = he;
}
public async Task<IActionResult> CreateV3EnterCheckFile(IFormFile MarksFile)
{
try
{
var filesCount = Directory.GetFiles("Uploads").Length;
string contentRootPath = _he.ContentRootPath;
string path = Path.Combine(contentRootPath +"\\Uploads", filesCount + 1 + ".xlsx");
await MarksFile.SaveToAsync(path);
var xlImporter = new XLImporter();
var importedData = await xlImporter.ImportSheetAsync(path, 0);
var r = (from x in importedData select new { ID = x[0], StudentId = x[1] }).ToList();
//System.IO.File.Delete(path);
if (File.Exists(path))
{
File.Delete(path);
}
else
{
Debug.WriteLine("File does not exist.");
}
return View();
}
catch(Exception e)
{
Console.WriteLine(e);
}
Or you can try another process:-
try
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.IO.File.Delete(path);
}
catch(Exception e){
}
}
Or this:-
if (System.IO.File.Exists(path))
{
try
{
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
System.IO.File.Delete(path);
}
catch (Exception e) { }
}
it should resolve your issue I hope. by the way, if your Upload folder is not under the webroot path. you can find your path using your process.
I have some data to save into a database.
I have created a web api post method to save data. Following is my post method:
[Route("PostRequirementTypeProcessing")]
public IEnumerable<NPAAddRequirementTypeProcessing> PostRequirementTypeProcessing(mdlAddAddRequirementTypeProcessing requTypeProcess)
{
mdlAddAddRequirementTypeProcessing rTyeProcessing = new mdlAddAddRequirementTypeProcessing();
rTyeProcessing.szDescription = requTypeProcess.szDescription;
rTyeProcessing.iRequirementTypeId = requTypeProcess.iRequirementTypeId;
rTyeProcessing.szRequirementNumber = requTypeProcess.szRequirementNumber;
rTyeProcessing.szRequirementIssuer = requTypeProcess.szRequirementIssuer;
rTyeProcessing.szOrganization = requTypeProcess.szOrganization;
rTyeProcessing.dIssuedate = requTypeProcess.dIssuedate;
rTyeProcessing.dExpirydate = requTypeProcess.dExpirydate;
rTyeProcessing.szSignedBy = requTypeProcess.szSignedBy;
rTyeProcessing.szAttachedDocumentNo = requTypeProcess.szAttachedDocumentNo;
if (String.IsNullOrEmpty(rTyeProcessing.szAttachedDocumentNo))
{
}
else
{
UploadFile();
}
rTyeProcessing.szSubject = requTypeProcess.szSubject;
rTyeProcessing.iApplicationDetailsId = requTypeProcess.iApplicationDetailsId;
rTyeProcessing.iEmpId = requTypeProcess.iEmpId;
NPAEntities context = new NPAEntities();
Log.Debug("PostRequirementTypeProcessing Request traced");
var newRTP = context.NPAAddRequirementTypeProcessing(requTypeProcess.szDescription, requTypeProcess.iRequirementTypeId,
requTypeProcess.szRequirementNumber, requTypeProcess.szRequirementIssuer, requTypeProcess.szOrganization,
requTypeProcess.dIssuedate, requTypeProcess.dExpirydate, requTypeProcess.szSignedBy,
requTypeProcess.szAttachedDocumentNo, requTypeProcess.szSubject, requTypeProcess.iApplicationDetailsId,
requTypeProcess.iEmpId);
return newRTP.ToList();
}
There is a field called 'szAttachedDocumentNo' which is a document that's being saved in the database as well.
After saving all data, I want the physical file of the 'szAttachedDocumentNo' to be saved on the server. So i created a method called "UploadFile" as follows:
[HttpPost]
public void UploadFile()
{
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
// Get the uploaded file from the Files collection
var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
string folderPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
//string folderPath1 = Convert.ToString(ConfigurationManager.AppSettings["DocPath"]);
//Directory not exists then create new directory
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
// Get the complete file path
var fileSavePath = Path.Combine(folderPath, httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
}
}
}
Before running the project, i debbugged the post method, so when it comes to "UploadFile" line, it takes me to its method.
From the file line, it skipped the remaining lines and went to the last line; what means it didn't see any file.
I am able to save everything to the database, just that i didn't see the physical file in the specified location.
Any help would be much appreciated.
Regards,
Somad
Makes sure the request "content-type": "multipart/form-data" is set
[HttpPost()]
public async Task<IHttpActionResult> UploadFile()
{
if (!Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
try
{
MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
if (provider.Contents != null && provider.Contents.Count == 0)
{
return BadRequest("No files provided.");
}
foreach (HttpContent file in provider.Contents)
{
string filename = file.Headers.ContentDisposition.FileName.Trim('\"');
byte[] buffer = await file.ReadAsByteArrayAsync();
using (MemoryStream stream = new MemoryStream(buffer))
{
// save the file whereever you want
}
}
return Ok("files Uploded");
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
I'm trying to set the wallpaper to an image on my Windows 10 device:
var fileName = postInf.title + ".jpg";
BitmapImage img = new BitmapImage();
bool success = false;
if (UserProfilePersonalizationSettings.IsSupported())
{
// read from pictures library
var pictureFile = await KnownFolders.PicturesLibrary.GetFileAsync(fileName);
using (var pictureStream = await pictureFile.OpenAsync(FileAccessMode.Read))
{
img.SetSource(pictureStream);
}
UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current;
success = await profileSettings.TrySetWallpaperImageAsync(pictureFile);
}
return success;
The storagefile is created fine, have tried with various images from various folders (e.g. My Pictures, Assets, LocalState); always returns false and wallpaper is not set? I have read/write permissions to pictures library, have tried running in debug and release versions. Apparently others are also having this problem.
Your app can't set wallpapers from any folder. Copy file in ApplicationData.Current.LocalFolder and set wallpaper from there.
My code:
if (list.SelectedIndex != -1)
{
var data = list.SelectedItem as ThumbItem;
StorageFile newFile = await data.File.CopyAsync(ApplicationData.Current.LocalFolder);
await SetWallpaperAsync(newFile);
}
async Task<bool> SetWallpaperAsync(StorageFile fileItem)
{
bool success = false;
if (UserProfilePersonalizationSettings.IsSupported())
{
UserProfilePersonalizationSettings profileSettings = UserProfilePersonalizationSettings.Current;
success = await profileSettings.TrySetWallpaperImageAsync(fileItem);
}
return success;
}
i have this c# code and i want to delete a certain sub directory in Documents Library. However this produces an error because the directory is not empty. I hope someone can guide me on how to do this.
thank you for any prompt reply.
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
var queryResult = storageFolder.CreateFolderQuery();
IReadOnlyList<StorageFolder> folderList = await queryResult.GetFoldersAsync();
foreach (StorageFolder folder in folderList)
{
await folder.DeleteAsync();
}
You could use the StorageFolder.GetFilesAsync() to obtain a list of all the files present in the folders and delete them prior to deleting the folders since there is no way in the DeleteAsync() method to specify subfolders and files.
More info: StorageFolder class | MSDN
Hope this may help.
public async void deletefile()
{
StorageFolder sourceFolder = ApplicationData.Current.TemporaryFolder;
// sourceFolder = await sourceFolder.GetFolderAsync("Test");
// await sourceFolder.DeleteAsync(StorageDeleteOption.PermanentDelete);
// var files = await sourceFolder.GetFilesAsync();
IReadOnlyList<StorageFile> folderList = await sourceFolder.GetFilesAsync();
if (folderList.Count > 0)
{
foreach (StorageFile f1 in folderList)
{
await f1.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
}
//StorageFile retfile = await ApplicationData.Current.TemporaryFolder.GetFileAsync("MysoundFile.mp3");
// if (retfile != null)
// {
// await retfile.DeleteAsync(StorageDeleteOption.PermanentDelete);
// }
}