Forum Xamarin.Android

copy file from Assets to local folder

monemdcmonemdc Member ✭✭✭

hi

I used the following code to transfer a file from Assest to Local folder and did not work for me.

`
public void copyfrom_assest()
{

        string fileName = "sample2010.txt";

        var localFolder = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
        var MyFilePath = System.IO.Path.Combine(localFolder, fileName);

        using (var streamReader = new StreamReader(Assets.Open(fileName)))
        {
            using (var memstream = new MemoryStream())
            {
                streamReader.BaseStream.CopyTo(memstream);
                var bytes = memstream.ToArray();
                //write to local storage
                System.IO.File.WriteAllBytes(MyFilePath, bytes);

                MyFilePath = $"file://{localFolder}/{fileName}";
            }
        }
    }

`

Tagged:

Best Answer

  • AlessandroCaliaroAlessandroCaliaro IT ✭✭✭✭✭
    Accepted Answer
        public static void CopyAssetFile(string from, string to)
        {
    
            // SE il file esiste, lo elimino
            if (System.IO.File.Exists(to))
                System.IO.File.Delete(to);
    
            using (var source = MainActivity.Instance.Assets.Open(from))
            {
                using (var dest = System.IO.File.Create(to))
                {
                    source.CopyTo(dest);
                }
            }
        }
    

Answers

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭
    Accepted Answer
        public static void CopyAssetFile(string from, string to)
        {
    
            // SE il file esiste, lo elimino
            if (System.IO.File.Exists(to))
                System.IO.File.Delete(to);
    
            using (var source = MainActivity.Instance.Assets.Open(from))
            {
                using (var dest = System.IO.File.Create(to))
                {
                    source.CopyTo(dest);
                }
            }
        }
    
Sign In or Register to comment.