How to relate between open file picker and storage file? - c#

look for this error and tell me your opinion to solve this problem
I was making window phone Application :
its can't save my picked file in a storage file to trim it as media
or I can not relate between open file picker and storage file if anyone have any ideas how to relate between them or have any demos please tell me

I'm not sure I understood your problem. Here is my code for picking a file and write into it in WinRT/Win10 store app.
private async void SaveFileExecute()
{
var fileNameTab = FileName.Split('.');
var extension = fileNameTab[1];
var fileName = fileNameTab[0];
var savePicker = new FileSavePicker
{
SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
SuggestedFileName = fileName
};
savePicker.FileTypeChoices.Add(extension, new List<string> { "." + extension });
var saveFile = await savePicker.PickSaveFileAsync();
if (saveFile != null)
{
using (var fileStream = await saveFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (var outputStream = fileStream.GetOutputStreamAt(0))
{
using (var dataWriter = new DataWriter(outputStream))
{
dataWriter.WriteBytes(SelectedFile.Data);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outputStream.FlushAsync();
}
}
}
}

Related

How to force delete a file used by another process in Asp.net core

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.

Having issue with with Progress Dialog using Acr.UserDialogs in xamarin forms iOS App

I am having a problem with showing progress bar using nuget package (Acr.UserDialog) in xamarin forms iOS. with the same code snippet, its working well in Android platform.
using (UserDialogs.Instance.Loading("Loading", null, null, true, MaskType.Black)) {
await Task.Run(() => {
// Code Logic Goes here ...
});
}
A version of ACR UserDialogs Library:
PCL Project - v6.5.1
iOS Project - v7.0.0
if anyone knows the solution for this issue, please provide a solution.
https://forums.xamarin.com/discussion/67832/implementing-file-picker-example-into-a-cross-platform-application
Please check this:
var file = await CrossFilePicker.Current.PickFile();
if (file != null)
{
var fileFullName = file.FilePath.Substring(file.FilePath.LastIndexOf('\\') + 1);
var extension = Path.GetExtension(file.FileName).Substring(1);
var fileName = Path.GetFileNameWithoutExtension("Pick_" + extension + "_File_" + DateTime.UtcNow.ToString("MMddyyyy_hhmmss"));
using (Stream stream = file.GetStream())
using (MemoryStream ms = new MemoryStream())
{
stream.CopyTo(ms);
filePath = ms.ToArray().SaveAttachmentInLocalFolder(fileName, extension);
}
}
public async Task GetPdfDataAsync(byte[] fileBytes)
{
try
{
var localPath = string.Empty;
var fileName = Guid.NewGuid().ToString();
localPath =
Task.Run(() => _localFileProvider.SaveFileToDisk(fileBytes, $"{fileName}.pdf")).Result;
if (string.IsNullOrWhiteSpace(localPath))
{
await PageDialogService.DisplayAlertAsync("Error loading PDF", "Computer says no", "OK");
return;
}
if (Device.RuntimePlatform == Device.Android)
Pdfviewsource = $"file:///android_asset/pdfjs/pdfjs/web/viewer.html?file={WebUtility.UrlEncode(localPath)}";
else
{
Pdfviewsource = localPath;
}
}
catch (Exception) { }
}

How to save image from clipboard to file in UWP

Is there any equivalent of
Clipboard.GetImage().Save(FileName, Imaging.ImageFormat.Jpeg)
for UWP (Windows Universal Platform)?
I.e. saving the graphics image from clipboard into jpg format to file.
I am looking for example in vb.net/C#.
I have already started with
Dim datapackage = DataTransfer.Clipboard.GetContent()
If datapackage.Contains(StandardDataFormats.Bitmap) Then
Dim r As Windows.Storage.Streams.RandomAccessStreamReference = Await datapackage.GetBitmapAsync()
...
but I do not know how to continue (and even if I have even started correctly).
The first step is to try and get the image from the clipboard, if it exists:
var dataPackageView = Windows.ApplicationModel.DataTransfer.Clipboard.GetContent();
if (dataPackageView.Contains(StandardDataFormats.Bitmap))
{
IRandomAccessStreamReference imageReceived = null;
try
{
imageReceived = await dataPackageView.GetBitmapAsync();
}
catch (Exception ex)
{
}
If it exists, launch a file save picker, choose where to save the image, and copy the image stream to the new file.
if (imageReceived != null)
{
using (var imageStream = await imageReceived.OpenReadAsync())
{
var fileSave = new FileSavePicker();
fileSave.FileTypeChoices.Add("Image", new string[] { ".jpg" });
var storageFile = await fileSave.PickSaveFileAsync();
using (var stream = await storageFile.OpenAsync(FileAccessMode.ReadWrite))
{
await imageStream.AsStreamForRead().CopyToAsync(stream.AsStreamForWrite());
}
}
}
}

Handling file in WP-- oplock broken

I am trying to, in some instances, read from, and in others, write to a file in Windows Phone 8.1. I am using the following code to read it:
var folder = ApplicationData.Current.LocalFolder;
try
{
var connectionsFile = await folder.OpenStreamForReadAsync("connections");
using (var streamReader = new StreamReader(connectionsFile, Encoding.Unicode))
{
while (!streamReader.EndOfStream)
{
String con = await streamReader.ReadLineAsync();
String[] props = con.Split('\t');
Connection newConnection = new Connection() { Name = props[0], Url = props[1] };
ConnectionsCollection.Add(newCollection);
}
await connectionsFile.FlushAsync();
connectionsFile.Dispose();
}
}
catch(Exception e)
{
//handle exception
}
My problem is that it unfailingly hits the catch with an inner exception of "The handle with which this oplock was associated has been closed. The oplock is now broken." (I get the same error when trying to write to it.) I can't figure out what the problem is, especially since I am successfully using the same code to read the same file in two other places.
I think you needs to remove the await connectionsFile.FlushAsync(); line because you're using the file for reading. Also remove the connectionsFile.Dispose(); and use the using(...) in connectionsFile assignment.
var folder = ApplicationData.Current.LocalFolder;
try
{
using (var connectionsFile = await folder.OpenStreamForReadAsync("connections"))
using (var streamReader = new StreamReader(connectionsFile, Encoding.Unicode))
{
while (!streamReader.EndOfStream)
{
String con = await streamReader.ReadLineAsync();
String[] props = con.Split('\t');
Connection newConnection = new Connection() {Name = props[0], Url = props[1]};
ConnectionsCollection.Add(newCollection);
}
}
}
catch (Exception e)
{
//handle exception
}
I hope it helps.

DownloadAsync result file is null

I use Live SDK 5.6 and I'm trying to download file from OneDrive. Using CreateBackgroundDownloadAsync (innerItem.ID + "/Content"), why is result file null?
foreach (var innerItem in resultItems.data)
{
if (innerItem.name == "MoneyNote.db")
{
LiveDownloadOperation operation = await liveConnectClient.CreateBackgroundDownloadAsync(innerItem.id + "/Content");
//LiveDownloadOperationResult downloadResult = await operation.StartAsync();
var downloadResult = await operation.StartAsync();
if (downloadResult.File != null)
{
StorageFile downFile = await ApplicationData.Current.LocalFolder.GetFileAsync("MoneyNote.db");
await downloadResult.File.MoveAndReplaceAsync(downFile);
messagePrint(true);
}
else
{
messagePrint(false);
}
}
}
I think the problem may be, because you are creating background download (not downloading in the background), then you start this download operation, but file needs time to be downloaded. In this case probably easier would be just to download a file like this:
foreach (var innerItem in resultItems.data)
{
if (innerItem.name == "MoneyNote.db")
{
StorageFile downFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("MoneyNote.db", CreationCollisionOption.ReplaceExisting);
var result = await liveConnectClient.BackgroundDownloadAsync(innerItem.id + "/content", downFile);
messagePrint(true);
}
}

Categories