File.Delete() throw "owner died" in Xamarin - xamarin

Generally, file deletion can be performed correctly on most Android phones
However, when I run this line of code on "Huawei art-al00x (Android 10.0 - API 29)", the operation throws an exception "owner died"
I can create files and write data, but I can't delete files
I've never been in this situation before
After Google searched, there is still no result
After the second test, I found that if I checked the file in the file manager, I could delete it smoothly, while if I didn't check the file, it would throw an exception
The Code:
string path = "Want Save Path";
byte[] buffer = new uint8_t[73790];
using (BinaryWriter BW = new BinaryWriter(new FileStream(path, FileMode.Create)))
{
BW.Write(buffer, 0, (int)exer.Size);
BW.Flush();
BW.Close();
Console.WriteLine("USM:Save Image Data Success");
}
StackTrace:
at System.IO.FileSystem.DeleteFile (System.String fullPath) [0x00065]
in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.IO.FileSystem/src/System/IO/FileSystem.Unix.cs:215
at System.IO.File.Delete (System.String path) [0x0000e]
in /Users/builder/jenkins/workspace/archive-mono/2020-02/android/release/external/corefx/src/System.IO.FileSystem/src/System/IO/File.cs:107
at DebugTest.MyView.MainPage_OperateView.TTTFrame_Click () [0x00014]
in G:\VS2019 Projects\DebugTest\DebugTest\DebugTest\MyView\MainPage_OperateView.xaml.cs:263

Related

Following Microsoft AZ-204 Learning Path, Encountered error "Unhandled exception. System.NotSupportedException: Stream does not support reading."

I am following the AZ-204: Develop solutions that use Blob storage / Work with Azure Blob storage tutorial located here.
The code is copy/paste but I have encountered an error. I am not a .net developer and I have no idea how to resolve this. Microsoft offers no troubleshooting resources with this self-led material. I'm hoping to find help for resolving this error.
The file I am attempting to run:
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
Console.WriteLine("Azure Blob Storage exercise\n");
// Run the examples asynchronously, wait for the results before proceeding
ProcessAsync().GetAwaiter().GetResult();
Console.WriteLine("Press enter to exit the sample application.");
Console.ReadLine();
static async Task ProcessAsync()
{
// Copy the connection string from the portal in the variable below.
string storageConnectionString = "[redacted]";
// Create a client that can authenticate with a connection string
BlobServiceClient blobServiceClient = new BlobServiceClient(storageConnectionString);
// COPY EXAMPLE CODE BELOW HERE
// CREATE A CONTAINER
//Create a unique name for the container
string containerName = "wtblob" + Guid.NewGuid().ToString();
// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
Console.WriteLine("A container named '" + containerName + "' has been created. " +
"\nTake a minute and verify in the portal." +
"\nNext a file will be created and uploaded to the container.");
Console.WriteLine("Press 'Enter' to continue.");
Console.ReadLine();
// UPLOAD BLOBS TO A CONTAINER
// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "./data/";
string fileName = "wtfile" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);
// Write text to the file
await File.WriteAllTextAsync(localFilePath, "Hello, World!");
// Get a reference to the blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);
// Open the file and upload its data
using (FileStream uploadFileStream = File.OpenWrite(localFilePath))
{
await blobClient.UploadAsync(uploadFileStream);
uploadFileStream.Close();
}
Console.WriteLine("\nThe file was uploaded. We'll verify by listing" +
" the blobs next.");
Console.WriteLine("Press 'Enter' to continue.");
Console.ReadLine();
// LIST THE BLOBS IN A CONTAINER
// List blobs in the container
Console.WriteLine("Listing blobs...");
await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
Console.WriteLine("\t" + blobItem.Name);
}
Console.WriteLine("\nYou can also verify by looking inside the " +
"container in the portal." +
"\nNext the blob will be downloaded with an altered file name.");
Console.WriteLine("Press 'Enter' to continue.");
Console.ReadLine();
// DOWNLOAD BLOBS
// Download the blob to a local file
// Append the string "DOWNLOADED" before the .txt extension
string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOADED.txt");
Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);
// Download the blob's contents and save it to a file
BlobDownloadInfo download = await blobClient.DownloadAsync();
using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
{
await download.Content.CopyToAsync(downloadFileStream);
}
Console.WriteLine("\nLocate the local file in the data directory created earlier to verify it was downloaded.");
Console.WriteLine("The next step is to delete the container and local files.");
Console.WriteLine("Press 'Enter' to continue.");
Console.ReadLine();
// DELETE A CONTAINER
// Delete the container and clean up local files created
Console.WriteLine("\n\nDeleting blob container...");
await containerClient.DeleteAsync();
Console.WriteLine("Deleting the local source and downloaded files...");
File.Delete(localFilePath);
File.Delete(downloadFilePath);
Console.WriteLine("Finished cleaning up.");
}
I am able to verify the container was created in the azure portal, then the code runs up to line 46 where "Uploading to Blob storage as blob:" is logged, then encounters the error.
The console output (including prior to the error):
Azure Blob Storage exercise
A container named 'wtblob167d9a9b-d4c0-4b2c-9ea3-21d2c90fd386' has been created.
Take a minute and verify in the portal.
Next a file will be created and uploaded to the container.
Press 'Enter' to continue.
Uploading to Blob storage as blob:
https://[redacted].blob.core.windows.net/wtblob167d9a9b-d4c0-4b2c-9ea3-21d2c90fd386/wtfilebfbd8b5e-d5b3-487c-885b-364db2fe126a.txt
Unhandled exception. System.NotSupportedException: Stream does not support reading.
at System.IO.Strategies.BufferedFileStreamStrategy.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
at System.IO.FileStream.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
at Azure.Storage.NonDisposingStream.CopyToAsync(Stream destination, Int32 bufferSize, CancellationToken cancellationToken)
at Azure.Core.RequestContent.StreamContent.WriteToAsync(Stream stream, CancellationToken cancellation)
at Azure.Core.Pipeline.HttpClientTransport.PipelineRequest.PipelineContentAdapter.SerializeToStreamAsync(Stream stream, TransportContext context, CancellationToken cancellationToken)
at System.Net.Http.HttpContent.<CopyToAsync>g__WaitAsync|56_0(ValueTask copyTask)
at System.Net.Http.HttpConnection.SendRequestContentAsync(HttpRequestMessage request, HttpContentWriteStream stream, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnection.SendAsyncCore(HttpRequestMessage request, Boolean async, CancellationToken cancellationToken)
at System.Net.Http.HttpConnectionPool.SendWithVersionDetectionAndRetryAsync(HttpRequestMessage request, Boolean async, Boolean doRequestAuth, CancellationToken cancellationToken)
at System.Net.Http.HttpClient.<SendAsync>g__Core|83_0(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationTokenSource cts, Boolean disposeCts, CancellationTokenSource pendingRequestsCts, CancellationToken originalCancellationToken)
at Azure.Core.Pipeline.HttpClientTransport.ProcessAsync(HttpMessage message, Boolean async)
at Azure.Core.Pipeline.HttpPipelineTransportPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline)
at Azure.Core.Pipeline.ResponseBodyPolicy.ProcessAsync(HttpMessage message, ReadOnlyMemory`1 pipeline, Boolean async)
at Azure.Core.Pipeline.HttpPipelineSynchronousPolicy.<ProcessAsync>g__ProcessAsyncInner|4_0(HttpMessage message, ReadOnlyMemory`1 pipeline)
onary`2 metadata, IDictionary`2 tags, BlobRequestConditions conditions, Nullable`1 accessTier, BlobImmutabilityPolicy immutabilityPolicy, Nullable`1 legalHold, IProgress`1 progressHandler, UploadTransferValidationOptions transferValidationOverride, String operationName, Boolean async, CancellationToken cancellationToken)
at Azure.Storage.Blobs.Specialized.BlockBlobClient.<>c__DisplayClass64_0.<<GetPartitionedUploaderBehaviors>b__0>d.MoveNext()
--- End of stack trace from previous location --- at Azure.Storage.PartitionedUploader`2.UploadInternal(Stream content, Nullable`1 expectedContentLength, TServiceSpecificData args, IProgress`1 progressHandler, Boolean async, CancellationToken cancellationToken) at Azure.Storage.Blobs.BlobClient.StagedUploadInternal(Stream content, BlobUploadOptions options, Boolean async, CancellationToken cancellationToken)
at Azure.Storage.Blobs.BlobClient.UploadAsync(Stream content) at Program.<<Main>$>g__ProcessAsync|0_0() in C:\Users\[redacted]\Documents\devops\working with blob storage module\az204-blob\Program.cs:line 51
at Program.<Main>$(String[] args) in C:\Users\[redacted]\Documents\devops\working with blob storage module\az204-blob\Program.cs:line 7
I copied the code from the tutorial and tried to run it following the given instructions. It starts out fine but throws an error when trying to upload the new file to the blob. I expected the new file to be written to the blob, and the remaining instructions to be executed.
I was able to repro the issue locally with the same code and after doing below changes I was able to upload it successfully:
Old Code:
// Open the file and upload its data
using (FileStream uploadFileStream = File.OpenWrite(localFilePath))
{
await blobClient.UploadAsync(uploadFileStream);
uploadFileStream.Close();
}
// Modified Code
FileStream uploadFileStream = File.Open(localFilePath, FileMode.Open);
blobClient.Upload(uploadFileStream);
uploadFileStream.Close();
Let me know if that helps !

Unable to get image after reinstalling the app

I am not able to get the images stored in Parse-Server as a file, once I reinstall the app. It works fine while a user is logged in but once the app is uninstalled only files are unable to access.It shows exception saying :- File doesn't exist . And I am not able to download image in parse server as well .It will redirect me to role section.
Tried changing version of parse in gradle.
I should be able to access images after reinstalling app. And I should be able to download image in parse.
code written to upload image-----------------------
ParseFile filename = new ParseFile("name.png", Byte);
filename.saveInBackground();
classObject.put("imagePic", filename);
classObject.saveInBackground();
Retrieving from Parse server--------------
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if(e == null) {
if(data != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,data.length);
imageView.setImageBitmap(bitmap);
}
}
});

I cannot access ApplicationData.Current from Win32 unpackaged app?

My code:
using System;
using Windows;
namespace SampleSynthesis {
class Program {
static async System.Threading.Tasks.Task Main(string[] args) {
var synth = new Windows.Media.SpeechSynthesis.SpeechSynthesizer();
Windows.Media.SpeechSynthesis.SpeechSynthesisStream stream =
await synth.SynthesizeTextToStreamAsync("I want to listen to this text");
using (var reader = new Windows.Storage.Streams.DataReader(stream)) {
await reader.LoadAsync((uint)stream.Size);
Windows.Storage.Streams.IBuffer buffer = reader.ReadBuffer((uint)stream.Size);
Windows.Storage.StorageFile file = await Windows.Storage.ApplicationData.Current.LocalFolder.CreateFileAsync("audio.wav");
await Windows.Storage.FileIO.WriteBufferAsync(file, buffer);
}
}
}
Compiled with this command:
"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin\Roslyn\csc.exe" /r:"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5.2\System.Speech.dll","C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5\System.Runtime.WindowsRuntime.dll","C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.runtime.dll","C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.17763.0\Windows.winmd","C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Threading.Tasks.dll" tts.cs
I am getting:
Unhandled Exception: System.InvalidOperationException: The process has no package identity. (Exception from HRESULT: 0x80073D54)
at Windows.Storage.ApplicationData.get_Current()
at SampleSynthesis.Program.<Main>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at SampleSynthesis.Program.<Main>(String[] args)
Maybe exists another way to save wav? I know that I can use simpler SetOutputToWaveFile() but because of cracks in the synthesized audio I want to try some another method. I need to use Desktop Bridge? Instead of Windows.Storage.ApplicationData.Current.LocalFolder I tried Windows.Storage.ApplicationData.Current.TemporaryFolder and got the same exception.
Windows.Storage.ApplicationData.Current only applies to packaged apps that have an identity (UWP apps and Desktop Bridge apps). Unpackaged Win32 EXE don't have the concept of their own isolated app data.
It's not clear why you need to this here, or what you are trying to accomplish. This shouldn't have anything to do with cracks in the audio playback.

Error on DeleteAsync fileStorage in windows fall creation update

With the upgrade to windows fall creation my application has a problem, when a file is deleted, it gives me an exception:
System.IO.FileLoadException: 'The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)'
The file is first copied to my directory and then deleted:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
if (e.Parameter != null)
{
folder = ApplicationData.Current.LocalFolder;
this.myfile= e.Parameter as MyFile;
this.view = await this.myfile.CopyAsync(folder, this.myfile.Name, NameCollisionOption.ReplaceExisting);
}
}
and before leave the view:
protected override async void OnNavigatedFrom(NavigationEventArgs e)
{
await this.view.DeleteAsync();
}
In windows creation update this work, in windows fall creation update not work.
Update:
I have analyzed the error, this is due to the use of the PdfDocument library.
var folder = ApplicationData.Current.LocalFolder;
StorageFile file = await folder.GetFileAsync("temp.pdf");
using (IRandomAccessStream filestream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
}
var pdfDocument = await PdfDocument.LoadFromFileAsync(file);
using (IRandomAccessStream filestream1 = await file.OpenAsync(FileAccessMode.ReadWrite))
{
}
the error occurs only when I open the file with OpenAsync (File Access Mode.ReadWrite); , if I open the view twice with the same file I get an error
If you mean open the file twice without disposing the first stream as the following code snippet showed, it do will throw the exception as you described in the thread.
await temp.OpenAsync(FileAccessMode.ReadWrite);
await temp.OpenAsync(FileAccessMode.ReadWrite);
maybe I need a method to close the file?
As you considered, you need to call the dispose method to allow the resources used by the Stream to be reallocated for other purposes. The stream will not be auto disposed until you invoke the dispose method, so that you cannot open the file stream again. For example, you should update your code snippet to:
StorageFile temp = await ApplicationData.Current.LocalFolder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);
IRandomAccessStream stream = await temp.OpenAsync(FileAccessMode.ReadWrite);
stream.Dispose();
IRandomAccessStream streamtwice= await temp.OpenAsync(FileAccessMode.ReadWrite);
streamtwice.Dispose();
Using statement provides a convenient syntax that ensures the correct use of IDisposable objects. It is recommended to use using statement instead, code as follows:
StorageFile temp = await ApplicationData.Current.LocalFolder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream stream = await temp.OpenAsync(FileAccessMode.ReadWrite))
{
}

File Overwrite issue when trying to transfer file using FTP

I have a FTP server with only List and Put permissions. But not having delete, overwrite and Rename permissions.
Now when I try to transfer a file using simple FTP using the following implementation
private boolean sendFileStreamHelper(InputStream inputStream, String nameOfFileToStore, String filetransferDestFolder) throws FileTransferException {
Log.info("Inside SendFile inputstream method to trasport the input stream of file " + nameOfFileToStore + " data to " + filetransferDestFolder);
BufferedOutputStream os = null;
FileObject fo = null;
try {
fo = getFileObject(nameOfFileToStore, filetransferDestFolder, ftpAuthDetails.getServerName(), ftpAuthDetails.getUsername(), ftpAuthDetails
.getPassword(), ftpAuthDetails.getPort());
fo.createFile();// create a file in the remote to transfer the file
os = new BufferedOutputStream(fo.getContent().getOutputStream());
FileUtil.readStream(inputStream, os);
return true;
} catch (Exception ex) {
Log.error("File transfer exception occurred while transferrig the file " + nameOfFileToStore + " to " + filetransferDestFolder, ex);
throw new FileTransferException(ex);
} finally {
if (os != null) {
try {
os.flush();
os.close();
} catch (IOException e) {
Log.warn(getClass(), " Error while closing the buffer output stream", e);
}
}
if (fo != null) {
try {
fo.close();
} catch (IOException e) {
Log.warn(getClass(), " Error while closing the File object", e);
}
}
closeCache(); // Close the VFS Manager instance
}
}
In the above code as the File is created in the remote using the File Object instance. Later to that I am trying to write the file with the Buffered stream. Here the systems acts as if it is writing to a file which is already created and as my server is not having any overwrite permission, throwing following error.
29 Jul 2012 21:03:06 [ERROR] FC_ClusteredScheduler_Worker-2(1) com.abc.filetransfer.FileTransferClient - .sendFileStreamHelper(FileTransferClient.java:170) - File transfer exception occurred while transferrig the file *******.txt to / ex-org.apache.commons.vfs2.FileSystemException: Could not write to "ftp://******:***#***.***.***.***/*********.txt"
org.apache.commons.vfs2.FileSystemException: Could not write to "ftp://******:***#***.***.***.***/*********.txt".
at org.apache.commons.vfs2.provider.AbstractFileObject.getOutputStream(AbstractFileObject.java:1439)
at org.apache.commons.vfs2.provider.DefaultFileContent.getOutputStream(DefaultFileContent.java:461)
at org.apache.commons.vfs2.provider.DefaultFileContent.getOutputStream(DefaultFileContent.java:441)
at com.abc.filetransfer.FileTransferClient.sendFileStreamHelper(FileTransferClient.java:164)
at com.abc.filetransfer.FileTransferClient.sendFile(FileTransferClient.java:131)
at com.abc.filetransfer.FileTransferClient.sendFile(FileTransferClient.java:103)
at com.abc.filetransfer.client.FTPTransferClient.sendFile(FTPTransferClient.java:65)
Caused by: org.apache.commons.vfs2.FileSystemException: Cant open output connection for file "ftp://******:***#***.***.***.***/*********.txt".
Reason: "**550 File unavailable. Overwrite not allowed by user profile**^M
at org.apache.commons.vfs2.provider.ftp.FtpFileObject.doGetOutputStream(FtpFileObject.java:648)
at org.apache.commons.vfs2.provider.AbstractFileObject.getOutputStream(AbstractFileObject.java:1431)
Please let me know how can I handle the file transfer using file Object, such that both File creation and writing the stream should happen at once.
I have resolved the issue.
Its pretty straight forward. In the below code
fo = getFileObject(nameOfFileToStore, filetransferDestFolder, ftpAuthDetails.getServerName(), ftpAuthDetails.getUsername(), ftpAuthDetails
.getPassword(), ftpAuthDetails.getPort());
fo.createFile();// create a file in the remote to transfer the file
os = new BufferedOutputStream(fo.getContent().getOutputStream());
FileUtil.readStream(inputStream, os);
I am creating a file first using the FileObject and then trying to write the BOS into the file.
Here while writing BOS to file system considers that we are trying to add data to a already existing file (as I am doing it in two separate steps, Creating a file and writing Data to the same) and returns the Error
**550 File unavailable. Overwrite not allowed by user profile*
I have removed the
fo.createFile()
as the BOS while writing the data will any way create a file if not available.
Thanks for your time.
Purushotham Reddy

Resources