Giter Club home page Giter Club logo

pclstorage's Introduction

PCL Storage

PCL Storage

PCL Storage provides a consistent, portable set of local file IO APIs for .NET, Windows Phone, Windows Store, Xamarin.iOS, Xamarin.Android, and Silverlight. This makes it easier to create cross-platform .NET libraries and apps.

Here is a sample showing how you can use PCL Storage to create a folder and write to a text file in that folder:

public async Task PCLStorageSample()
{
    IFolder rootFolder = FileSystem.Current.LocalStorage;
    IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder",
        CreationCollisionOption.OpenIfExists);
    IFile file = await folder.CreateFileAsync("answer.txt",
        CreationCollisionOption.ReplaceExisting);
    await file.WriteAllTextAsync("42");
}

Installation

Install the PCLStorage NuGet Package.

If you reference the package from a Portable Class Library, you will also need to reference the package from each platform-specific app. This is because the Portable Class Library version of PCL Storage doesn't contain the actual implementation of the storage APIs (because it differs from platform to platform), so referencing the package from an app will ensure that the platform-specific version of PCL Storage is included in the app and used at runtime.

Background information

Different .NET platforms have different APIs for accessing the file system or an app-local persisted storage area. The full .NET Framework provides the standard file and directory APIs (in the System.IO namespace), Silverlight and Windows Phone provide isolated storage APIs, and WinRT provides storage APIs in the Windows.Storage namespace.

These differing APIs make it harder to write cross-platform code. Traditionally, you could handle this via conditional compilation. However, that means you can't take advantage of Portable Class Libraries, and in any case may not scale well as your code gets complex (and especially because for WinRT you need to use async APIs).

Alternatively, you can create an abstraction for the functionality you need across platforms, and implement the abstraction for each platform you need to use. This approach allows you to use Portable Class Libraries, and in general makes your code cleaner and more maintainable by isolating the platform-specific pieces instead of having them sprinkled arbitrarily throughout your code.

Writing an abstraction layer is a bit of a barrier to entry to writing cross-platform code, and there's no reason everyone should have to do it separately for functionality as commonly needed as local file IO. PCL Storage aims to provide a common abstraction that is easy to take advantage of.

APIs

API documentation for PCL Storage can be found at NuDoq. The definitions for the main APIs in PCL Storage are below.

The primary APIs in PCL Storage are the IFile, IFolder, and IFileSystem interfaces. The APIs should be mostly self-explanatory and should feel very familiar if you have used the WinRT storage APIs.

The IFileSystem interface is the main API entry point. You can get an instance of the implementation for the current platform with the FileSystem.Current property.

namespace PCLStorage
{
    public static class FileSystem
    {
        public static IFileSystem Current { get; }
    }

    public interface IFileSystem
    {
        IFolder LocalStorage { get; }
        IFolder RoamingStorage { get; }

        Task<IFile> GetFileFromPathAsync(string path);
        Task<IFolder> GetFolderFromPathAsync(string path);
    }

    public enum CreationCollisionOption
    {
        GenerateUniqueName = 0,
        ReplaceExisting = 1,
        FailIfExists = 2,
        OpenIfExists = 3,
    }

    public interface IFolder
    {
        string Name { get; }
        string Path { get; }

        Task<IFile> CreateFileAsync(string desiredName, CreationCollisionOption option);
        Task<IFile> GetFileAsync(string name);
        Task<IList<IFile>> GetFilesAsync();

        Task<IFolder> CreateFolderAsync(string desiredName,
            CreationCollisionOption option);
        Task<IFolder> GetFolderAsync(string name);
        Task<IList<IFolder>> GetFoldersAsync();

        Task<ExistenceCheckResult> CheckExistsAsync(string name,
            CancellationToken cancellationToken = default(CancellationToken));

        Task DeleteAsync();
    }

    public enum FileAccess
    {
        Read,
        ReadAndWrite
    }

    public interface IFile
    {
        string Name { get; }
        string Path { get; }

        Task<Stream> OpenAsync(FileAccess fileAccess);
        Task DeleteAsync();
        Task RenameAsync(string newName,
          NameCollisionOption collisionOption = NameCollisionOption.FailIfExists,
          CancellationToken cancellationToken = default(CancellationToken));
        Task MoveAsync(string newPath,
          NameCollisionOption collisionOption = NameCollisionOption.ReplaceExisting,
          CancellationToken cancellationToken = default(CancellationToken));
    }

    public static class PortablePath
    {
        public static char DirectorySeparatorChar { get; }
        public static string Combine(params string[] paths);
    }
    public static class FileExtensions
    {
        public static async Task<string> ReadAllTextAsync(this IFile file)
        public static async Task WriteAllTextAsync(this IFile file, string contents);
    }
}

pclstorage's People

Contributors

aarnott avatar danrigby avatar dsplaisted avatar jamesmontemagno avatar jkennedy24 avatar mattleibow avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pclstorage's Issues

RoamingStorage on Android/iOS gets "System.NullReferenceException: Object reference not set to an instance of an object"

Hi,

Relatively new to Xamarin. Trying PCLstorage as a quick and easy way to get text files working. Have succeeded with using LocalStorage on Android/iOS/UWP, however comes up with "System.NullReferenceException: Object reference not set to an instance of an object" if I try to use RoamingStorage on Android/iOS (it does work for UWP however). I am wanting to have user-accessible files, and I'm presuming using the RoamingStorage option is the way to do it? (LocalStorage is definitely NOT user-accessible on Android - doesn't seem to matter with UWP).

How to unit test?

Im trying to use this as part of a PCL which will be referenced by my app's core PCL. I'd like to write unit tests for the processes my library controls but Im not sure if there is a way to unit test the storage part.

Would I just mock the storage methods?

Thanks,
Jason

large internal fragmentation

I am using PCLStorage to store files that are send across a network. It works by braking up a large file into many file parts. The file parts are then sent one by one across the network. The client receiving each file part and writes it to the file stream.

The problem is writing small chunks of the file means the OS has no idea how big the complete file will be and therefore makes a poor judgement on how much space to allocate for the file. Just to make sure we are on the same page this wasted space inside a file is called internal fragmentation.

https://puu.sh/tCrgT/28ac28e4ec.png

above is a screenshot of a file I sent across a network. On the left is the original file. On the right is the reconstructed file that has been sent with many parts across the network. The original uses 460KB of allocated memory while the file on the left uses 688KB of allocated memory. Therefore 49% of extra memory is needed for the same file.

my question is can I use your library to indicate to the OS the expected file size?

Can't access Documents folder in iOS

Terrific package but unfortunately it appears there is no way to store files in the iOS Documents folder. This is critical because if your app needs to allow users to sync files via iTunes, the files must be placed in Documents, not Library -- an iOS restriction. Unable to use PCLStorage for this reason. A third mode after LocalStorage and RoamingStorage is needed : - for Android it would be the same as Local, for iOS it would point to Documents.

CheckExistsAsync documentation

Hi,
Thanks for the great project.
the "CheckExistsAsync" function does not clearly mention that it checks for a folder relative to :

FileSystem.Current.LocalStorage

e.g.

            var rootFolder = FileSystem.Current.LocalStorage;
            var exist = await rootFolder.CheckExistsAsync("DB");

and that it will not work if i give it:

            var rootFolder = FileSystem.Current.LocalStorage;

            var dbPath = PortablePath.Combine(rootFolder.Path, "DB");

            var exist = await rootFolder.CheckExistsAsync(dbPath);

as the "dbPath" is going to have a full path.

which gives a lot of headache before discovering it, at least it did for me.
Wither that, or allow the "CheckExistsAsync" to work with the passed full path if its path contained in the passed one.

Xamarin.Mac support

Xamarin.Mac version doesn't work proper way(for example, LocalStorage returns ~/../Library, which incorrect by definition). Here you can find fork, which repairs Mac compatibility

IOS submission issues

hi,
I use pclstorage to store images. All was working fine.
But suddenly Apple requires that i "tag" the files as "do not backup".
https://developer.apple.com/icloud/documentation/data-storage/index.html
the third case.

It seems to be required in order to not having the files ending in the icloud of the user.
i need those files in the local storage for offline usage.
i did not find where and if the pclstorage can set this attribute.

thanx.

Adroid write to files.

Having problems writing then reading files Xamarian Android application.

Its the same issue posted to here....
http://stackoverflow.com/questions/21999804/cross-platform-solution-to-isolated-storage-in-pcl/37439443#37439443

I have my permissions set correctly to read/write external storage in my android manifest file.

Reading the data I get this exception
ex {PCLStorage.Exceptions.FileNotFoundException: File does not exist: /data/data/com.bconnect.expo/files…} PCLStorage.Exceptions.FileNotFoundException

This is after the write appears to be successful.

Shouldn't the file name be '/Android/data/com.bconnect.expo/files....' ?

Here is my code, as you can see I'm not doing really anything more than what the examples give

    private async void writeDeviceData ()
    {
        IFolder rootFolder = FileSystem.Current.LocalStorage;

        //load everything into a dictionary
        Dictionary<string,string> expoContents = new Dictionary<string, string>();

                    //omitted.... for size

        //create file
        IFile outFile = await rootFolder.CreateFileAsync("ExpoFile.txt", CreationCollisionOption.ReplaceExisting);

        //write to file
        var strContents = JsonConvert.SerializeObject(expoContents);

        try
        {
            await outFile.WriteAllTextAsync( strContents );

        }
        catch(Exception ex) 
        {

        }

    }

    private async void readDeviceData ()
    {

        IFolder rootFolder = FileSystem.Current.LocalStorage;

        try{
            IFile inFile = await rootFolder.GetFileAsync("Expofile.txt");
            string strContents = inFile.ReadAllTextAsync ().Result;
                              //...omitted for size
            }
        }
        catch ( Exception ex)
        {
            //go out to web service
            reloadSiteData ();
        }

    }

Request to expose the current platform type

First, thanks for a really useful library. It's really easy to use and 'does what it says on the box'.

I have a feature request. It would be very useful to support a property that provides the current platform type (or FileSystemType). As the library provides platform specific implementations of the interfaces, it should be trivial to add in support to the FileSystem class or IFileSystem interface to expose the current platform type (i.e. Android, IOS, or WinPhone).

I added a property to my access wrapper by inferring the platform from the last folder in FileSystem.Current.LocalStorage.Path, but it would be much better and more maintainable to have it included in the library based on the implementation of an interface..

Thanks again for a great library

David

Convert IFile to IStorageFile on WinRT

Is there a way to convert the IFile object back to IStorageFile?
I'm using new PCLStorage.WinRTFile(file) to create an IFile reference from a StorageFile, but I don't see a way of getting the wrapped object back. Have you considered providing a method for retrieval, eg. by casting to WinRTFile, or better yet, via an extension method?

Write many lines in file

Hi for everybody

I'm not sure if this issue is my error or a library error, but i'm trying to write a file log, but the funcion overwrite the first line always, initialy i was using the funcion IFile.WriteAllTextAsync(text) but it overwrite but if i use a streamwriter, the file no change, this is my code.

the file object is the type IFile

using (var stream = await file.OpenAsync(FileAccess.ReadAndWrite))
{
using (var writer = new StreamWriter(stream))
{
writer.WriteLine(data);
writer.Flush();
}
}

Looking for synchronous API

Now that Universal Windows has support for returning to the System.IO.File, etc. API's with their synchronous method calls, we would like to see support in PCLStorage for synchronous calls. We think it preferable to retain the use of synchronous file IO patterns in Android and iOS code and update asynchronous Windows IO patterns to match that (rather than introduce the complexity of asynchronous file IO patterns into Android and iOS code). What is your opinion? Are there plans to support this in PCLStorage?

/Documents/../Library Path on IOS

I am getting /var/mobile/Containers/Data/Application/22FAAA71-766D-45CD-9349-C16547432F7B/Documents/../Library as my path on IOS. The .. seems to create problems with other parts of the app trying to use the Path.

Why am I getting "/Documents/../Library" instead of just "/Library"? And how can I fix it?

Thanks
M

Feature Request: Add IFileSystem.RemoveableStorage

  1. It looks like this project is a little dormant at the moment. I saw reference to System.IO.File being made portable... until then I need a portable solution, and this looks pretty good, except for accessing removable storage (SD cards, etc).

I don't see anything for that in the current API, so if it exists, please point me in the right direction.

Assuming it would be a new feature, I need access to Removable storage, and I know there isn't a real use case for iOS, but most other platforms do support it, and it would be extremely useful my more than one of my apps.

It seems like it would be a rather easy thing to add, and simply throw a NotSupportedException for iOS, even though I wouldn't expect anyone to try.

I may add it myself and send a pull request, if there are no plans or alternatives found.

System.MemberAccessException due to AssemblyCompany not set in AssemblyInfo.cs

While trying to check whether or not a folder exists from a PCL library through a Unit Test target via SpecialFolder.Current.Cache.CheckExistsAsync("MyFolder") I get the following exception being thrown, which cases my unit test to fail:

System.MemberAccessException : There is a need to set a valid value to AssemblyCompany of AssemblyInfo.cs.

Stack trace:

  at PCLStorage.FolderPathImplementation.get_CompanyName () [0x00026] in <8863a90a3bb844dc851b55584719db5c>:0 
  at PCLStorage.FolderPathImplementation.GetPath (System.Environment+SpecialFolder specialFolder, System.String subFolder) [0x00011] in <8863a90a3bb844dc851b55584719db5c>:0 
  at PCLStorage.FolderPathImplementation.get_Cache () [0x00000] in <8863a90a3bb844dc851b55584719db5c>:0 
  at PCLStorage.SpecialFolderImplementation+<>c.<.ctor>b__28_4 () [0x00005] in <350c568532c8492b932e1f1f3b4a07fa>:0 
  at System.Lazy`1[T].CreateValue () [0x00075] in /private/tmp/source-mono-4.8.0/bockbuild-mono-4.8.0-branch/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/Lazy.cs:437 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /private/tmp/source-mono-4.8.0/bockbuild-mono-4.8.0-branch/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143 
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /private/tmp/source-mono-4.8.0/bockbuild-mono-4.8.0-branch/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187 
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /private/tmp/source-mono-4.8.0/bockbuild-mono-4.8.0-branch/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156 
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /private/tmp/source-mono-4.8.0/bockbuild-mono-4.8.0-branch/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128 
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /private/tmp/source-mono-4.8.0/bockbuild-mono-4.8.0-branch/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357 
  at DrinkUpLondon.Services.Rest.Tests.FileCacheProviderTests+<TestCaching>c__async0.MoveNext () [0x000fa] in /Users/jaderfeijo/Dropbox (Personal)/Development/Xamarin/drinkuplondon/DrinkUpLondon.Tests/Sources/Tests/Services/Rest/FileCacheProviderTests.cs:25 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /private/tmp/source-mono-4.8.0/bockbuild-mono-4.8.0-branch/profiles/mono-mac-xamarin/build-root/mono-x86/mcs/class/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143 
  at NUnit.Framework.Internal.ExceptionHelper.Rethrow (System.Exception exception) [0x00006] in <a136915bdafc4f7db46d0b0a906d5367>:0 
  at NUnit.Framework.Internal.AsyncInvocationRegion+AsyncTaskInvocationRegion.WaitForPendingOperationsToComplete (System.Object invocationResult) [0x00030] in <a136915bdafc4f7db46d0b0a906d5367>:0 
  at NUnit.Framework.Internal.Commands.TestMethodCommand.RunAsyncTestMethod (NUnit.Framework.Internal.TestExecutionContext context) [0x00038] in <a136915bdafc4f7db46d0b0a906d5367>:0 

No way to create-or-open file from path?

There is IFileSystem.GetFileFromPathAsync(), but if the file doesn't exist it returns null - there is no way to have it create the file.

There is IFolder.CreateFileAsync(), which has an option to open the file if it already exists, but in order to call it you need the IFolder first. You could load that using IFileSystem.GetFolderFromPathAsync() if you knew the folder's path, but if you only know the file's path you're out of luck - there is no way to obtain the folder path given the file path (I would expect that to be a method in PortablePath, but no such method exists).

Given how extremely common of a use-case this is, this seems like a huge gap in the API.

Unable to install nuget in Xamarin Android/IoS/IoS.Unified

Hi,

I'm trying to install the nuget in some Xamarin projects, but I get the following error:

System.InvalidOperationException: Could not install package 'Microsoft.Bcl.Build 1.0.14'. You are trying to install this package into a project that targets 'Xamarin.iOS, Version=v1.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author.
   at NuGet.PackageManagement.NuGetPackageManager.<ExecuteNuGetProjectActionsAsync>d__d2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.PackageManagement.UI.UIActionEngine.<ExecuteActions>d__1b.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at NuGet.PackageManagement.UI.UIActionEngine.<PerformAction>d__0.MoveNext()

Need simple example of checking if a FIle Exists on Windows in a PCL Analyzer VSIX

I think I need the code below

           Dim f As IFolder = Await FileSystem.Current.LocalStorage.GetFolderAsync(IO.Path.GetDirectoryName(context.Document.FilePath), context.CancellationToken)
            Dim r As ExistenceCheckResult = Await f.CheckExistsAsync(newFileName, context.CancellationToken)
            If r = ExistenceCheckResult.FileExists Then

but when I run it in the debugger I get this message on the first line

"This functionality is not implemented in the portable version of this assembly.  You should reference the PCLStorage NuGet package from your main application project in order to reference the platform-specific implementation."

What does this mean and how do I fix it? I don't need this in the VSIX project because it is not a PCL and the PCL project can't access the VSIX project.

Binaries Not Copied for UWP

Hi - I've built a UWP Class Library and added a reference to the PCLStorage NuGet package. But the

  • PCLStorage.Abstractions.dll
  • PCLStorage.Abstractions.xml
  • PCLStorage.dll
  • PCLStorage..xml

files are not getting copied to the respective Debug nor Release folders. This is not a problem for Android and iOS libraries.

My UWP project targets Windows 10 (10.0; Build 10586) and the projects.json file specifies
{
"dependencies": {
"Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0",
"PCLStorage": "1.0.2"
},
"frameworks": {
"uap10.0": {}
},
"runtimes": {
"win10-arm": {},
"win10-arm-aot": {},
"win10-x86": {},
"win10-x86-aot": {},
"win10-x64": {},
"win10-x64-aot": {}
}
}

I'm trying to package my own NuGet PCL and the missing PCLStorage files should be included. But I don't know where to pick them up from for UWP.

Thanks.

CreateFolderAsync not working on UWP with spaces in the path

If i call the following:

var res = myFolder.CreateFolderAsync(dir, CreationCollisionOption.OpenIfExists).Result;

where the Path is:

"C:\\Users\\My Admin\\AppData\\Local\\Packages\\guid\\LocalState\\App\\Folder"

Note the space in my "User"

I get the following exception:

The filename, directory name, or volume label syntax is incorrect. (Exception from HRESULT: 0x8007007B)
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at PCLStorage.WinRTFolder.d__12.MoveNext()

I guess its down to the space in my path

Check if storage is full

Is there a way to check if the storage is full with this plugin? I haven't seen anything in the docs.

Xamarin Windows Phone 8.1 issue

Hi,

I'm using PclStorage in a Xamarin Forms project, it works great for Android & iOS version on my app.
But i have an issue with the Windows Phone 8.1 version.
I had the plugin in the wp project and have an System.NotImplementedException error when trying to access FileSystem.Current

I saw online that set the CopyLocal to false for the plugin in the pcl project fix it for some people but not for me. But i have not seen any post about the windows phone 8.1 version.
Is the plugin working on that OS version ? If yes, how should i fix my problem ?

Regards.

EDIT :
I just found these line in the WindowsPhone project of the plugin :
<TargetFrameworkVersion>v8.0</TargetFrameworkVersion>

Does that mean that WP 8.1 is not supported right now ?

FileSystem.Current.LocalStorage.CheckExistAsync does not parse paths

I have an issue with CheckExistAsync. If the path given to it is not a single-tag one (e.g. "file.xml"), but a deeper one (e.g. "path\to\file.xml"), it does not work, throws an exception.

For generic checking I suggest to make CheckExistAsync recursive to be able to process paths that have a depth larger than one.

Version 1.0.2 can't be installed in Xamarin Studio

When searching Nuget from Xamarin Studio, all I get is version 0.9.6.
I tried to manually configure version 1.0.2 in packages.config like so:

<package id="PCLStorage" version="1.0.2" targetFramework="MonoAndroid41" />

However, this just gives an error:

Unable to find version '1.0.2' of package 'PCLStorage'.

I'm guessing this is related to #2, but I would think that release fixes this issue. I'm running Xamarin Studio 5.8.3 on Mac OSX.

Example not working on Android

I ran the example provided but I am not getting a folder or file created on sd card. I have permissions in manifest for read and write external storage. Still the same results.

Freeze when trying to check a file exists

ITNOA

Hi,

When I try to check exists file such as below code

public static async Task<Stream> GetStreamAsync(string path)
{
    IFolder rootFolder = FileSystem.Current.LocalStorage;
    ExistenceCheckResult isExistFile = await rootFolder.CheckExistsAsync(path);
    if (isExistFile == ExistenceCheckResult.NotFound)
        throw new FileNotFoundException($"path: {path}");
    IFile file = await rootFolder.GetFileAsync(path);
    return await file.OpenAsync(FileAccess.Read);
}

My platform:

  • Visual studio 2015 update 3
  • Xamarin forms
  • UWP app

My process freeze, I found one problem similar to me from here.

How to remove the version number as a folder from the path generated in PC?

I have been using PCLStorage in my application, it works fine but the thing is i cannot access the data as i change my application version number, the path also changes. I am storing my application data using this

IFolder rootFolder= FileSystem.Current.LocalStorage;

this return ..\AppData\Local\CompanyName\AppName\VersionNumber as path
but once i change version number access to my previous version data is not possible. Could you please suggest me what to do or guide me through it? However I would like to do this on PCL level.

Copy and Append Text

I may be overlooking this feature, but it would be great to include methods to copy a file and append text and/or bytes to a file.

iOS reference to Bcl.Async won't install

I get the below error when trying to add to my project.
(same for the referenced v165, here I tried the latest Bcl.Async)

PCLStorage cannot be used then right?
This is a Xamarin Forms app, and it's only adding it to the iOS app that fails.

Is there a way around this?

Thanks!

Severity Code Description Project File Line
Error Could not install package 'Microsoft.Bcl.Async 1.0.168'. You are trying to install this package into a project that targets 'Xamarin.iOS, Version=v1.0', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, contact the package author. 0

Xamarin.Mac - PCLStorage.dll Could Not Load "Systems.Windows.Forms"

I built a Xamarin.Mac test app which targets Xamarin.Mac, .NET 4.5 which references a Xamarin.Mac class library which targets the same. The library pulls in the latest, stable PCLStorage NuGet from NuGet.org. But when I run the app, I get an immediate System.IO.FileNotFoundException in Main() with this message.

Could not load file or assembly 'System.Windows.Forms' or one of its dependencies.

I've commented out most of the code in the library and I believe I've isolated the offending statement to this line.

var folder = FileSystem.Current.LocalStorage;

When it fails, the last line in the Application Output window shows

Loaded assembly..../MonoBundle/PCLStorage.dll [External]

If I comment the line out, the app starts up just fine and the Output does NOT show PCLStorage.dll being loaded at all. PCLStorage.Abstractions.dll [External] loads with no problems.

I'm running Xamarin Studio 5.10.3 (build 51) with Xamarin.Mac Version 2.4.2.1 (Xamarin Enterprise), and a colleague can reproduce the same problem in their dev environment running the same project.

No problem on iOS, Android, and Windows.

I've been debugging this for days now. Do you have a clue as to what my problem might be?

Thanks

IFile.MoveAsync() doesn't work in UWP

I used Media Plugin to pick a single picture.
I'm trying to move this picture to LocalStorage using MoveAsync().

Exception thrown: 'System.InvalidOperationException' in System.IO.FileSystem.dll
Exception thrown: 'System.InvalidOperationException' in mscorlib.ni.dll
Exception thrown: 'System.InvalidOperationException' in mscorlib.ni.dll

System Argumentexception in CheckExistsAsync in Xamarin.Forms UWP Project

Hi,

I'm trying to port my Xamarin Forms Android App to UWP. Unfortunately I get this exception while trying to check if a file in exists (which it doesn't).

Two things irritate me. first why at all is an exception thrown, And why it's an 'System.ArgumentException.

I found out, that UWP unlike Android throws an exception if the directory of the file that is checked does not exist.

'BREADy.UWP.exe' (CoreCLR: CoreCLR_UWP_Domain): Loaded 'Anonymously Hosted DynamicMethods Assembly'. 
The thread 0xb6c has exited with code 0 (0x0).
The thread 0x10a0 has exited with code 0 (0x0).
Step into: Stepping over non-user code 'BREADy.Model.FileStorage.CheckFileExists'
Step into: Stepping over non-user code 'BREADy.Model.FileStorage.<CheckFileExists>d__12..ctor'
The thread 0x124c has exited with code 0 (0x0).
Exception thrown: 'System.ArgumentException' in mscorlib.ni.dll
WinRT information: Ein Element mit dem angegebenen Namen (ingredients/ingredients.json) kann nicht gefunden werden.
Exception thrown: 'System.ArgumentException' in mscorlib.ni.dll
WinRT information: Ein Element mit dem angegebenen Namen (ingredients/ingredients.json) kann nicht gefunden werden.
Exception thrown: 'System.ArgumentException' in mscorlib.ni.dll
WinRT information: Ein Element mit dem angegebenen Namen (ingredients/ingredients.json) kann nicht gefunden werden.



   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at PCLStorage.WinRTFolder.<CheckExistsAsync>d__24.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at BREADy.Model.FileStorage.<CheckFileExists>d__12.MoveNext()

Spurious character in output file

The following statement:

           await file.WriteAllTextAsync ( "19°C" );

writes a file whose contents are "19°C".

The spurious introduced character, Â, is hex C2. Xamarin Forms iOS.

Reading file from local storage fails on UWP

After creating a path using the PortablePath and passing in LocalStorage, I am only able to access it if I use GetFileFromPathAsync. It fails when I use LocalStorage.GetFileAsync. It wo

   string path = PortablePath.Combine(FileSystem.Current.LocalStorage.Path, model.filename);
   
   //Succeeds on UWP, iOS, and Android
   IFile file = await FileSystem.Current.GetFileFromPathAsync(path);
   
   //Fails on UWP, succeeds on iOS and Android
   IFile file = await FileSystem.Current.LocalStorage.GetFileAsync(path);

System.IO.IOExceptionSharing violation on path /data/data/de.foo.android/files/carts/foobar.json

Hey Daniel,
we got in some cases an error.
At the most times we got it when the app is in background.

Do you know something about this kind of error?

public async Task Save(string path, string content) 
{
    var subFolder = await rootFolder.CreateFolderAsync(Path.GetDirectoryName(path), CreationCollisionOption.OpenIfExists);
    var file = await subFolder.CreateFileAsync(Path.GetFileName(path), CreationCollisionOption.ReplaceExisting);
    await file.WriteAllTextAsync(content);    
}
at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, Boolean anonymous, FileOptions options) [0x00000] in <filename unknown>:0 
  at System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share) [0x00000] in <filename unknown>:0 
  at System.IO.File.Open (System.String path, FileMode mode, FileAccess access) [0x00000] in <filename unknown>:0 
  at PCLStorage.FileSystemFile+<OpenAsync>d__0.MoveNext () [0x00000] in <filename unknown>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0 
  at System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1+ConfiguredTaskAwaiter[System.IO.Stream].GetResult () [0x00000] in <filename unknown>:0 
  at PCLStorage.FileExtensions+<WriteAllTextAsync>d__7.MoveNext () [0x00000] in <filename unknown>:0 
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x00000] in <filename unknown>:0 
  at System.Runtime.CompilerServices.TaskAwaiter.GetResult () [0x00000] in <filename unknown>:0 
  at Foo.Common.Storage.FileStorage+<Save>c__async0.MoveNext () [0x00000] in <filename unknown>:0 

Acces to install path

IMO there should be a way to access the install location using PCLStorage. It is only a folder.

There is in Android, Windows phone, windows rt, windows universal, Silverlight, win 32, etc.

but there isn't in PCL Storage.

ASP.NET Core 5.0

hello is it not supported?
i am not able to link PCLStorage, PCL Library included in asp.net is throwing an error "This functionality is not implemented in the portable version of this assembly. You should reference the PCLStorage NuGet package from your main application project in order to reference the platform-specific implementation."

CopyAsync

Is it possible to add a CopyAsync method to IFile?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.