Copy file from asset folder to external android memory unity - c#

I want to have some of my files in my assets folder to be copied to the android device. How do you do it?
I have tried several ways, like opening the files via debugging, it works in the PC. But when I have transferred it to the android device, it doesn't work or either copy it whatnot.
public void OpenPDF(string filename) //this opens the file I have in my pc. Via debugging in Unity.
{
TextAsset pdfTem = Resources.Load("PDFs/" + filename, typeof(TextAsset)) as TextAsset;
System.IO.File.WriteAllBytes(Application.persistentDataPath + "/" + filename + ".pdf", pdfTem.bytes);
Application.OpenURL(Application.persistentDataPath + "/" + filename + ".pdf");
}
public void openPDFfromSD()
{
Application.OpenURL("/mnt/sdcard/openme.pdf"); //this doesn't open the PDF file I have in my sd card.
}
public void legitOpen(string nameOfFile) //this opens the file I have in my pc. Via debugging in Unity.
{
string realPath = Application.persistentDataPath + "/" + nameOfFile + ".pdf";
if (!System.IO.File.Exists(realPath))
{
if (!System.IO.Directory.Exists(Application.persistentDataPath + "/PDFs/"))
{
System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/PDFs/");
}
WWW reader = new WWW(Application.streamingAssetsPath + "/PDFs/" + realPath);
while (!reader.isDone) { }
System.IO.File.WriteAllBytes(realPath, reader.bytes);
}
Application.OpenURL(realPath);
}

In general you shouldn't use string concatenation directly to build system paths.
Rather always use Path.Combine which automatically uses the correct path separator (/ or \) according to your target platform.
Also later in new WWW you have added both the leading Application.streamingAssetsPath and Application.persistentDataPath already in realPath.
public void OpenPDF(string filename)
{
TextAsset pdfTem = Resources.Load("PDFs/" + filename, typeof(TextAsset)) as TextAsset;
var filePath = Path.Combine(Application.persistentDataPath, filename + ".pdf";
System.IO.File.WriteAllBytes(filePath), pdfTem.bytes);
Application.OpenURL(filePath);
}
public void legitOpen(string nameOfFile)
{
string realPath = Path.Combine(Application.persistentDataPath, nameOfFile + ".pdf");
if (!System.IO.File.Exists(realPath))
{
if (!System.IO.Directory.Exists(Path.Combine(Application.persistentDataPath, "PDFs"))
{
System.IO.Directory.CreateDirectory(Path.Combine(Application.persistentDataPath, "PDFs"));
}
WWW reader = new WWW(Path.Combine(Application.streamingAssetsPath, "PDFs", nameOfFile + ".pdf");
while (!reader.isDone) { }
System.IO.File.WriteAllBytes(realPath, reader.bytes);
}
Application.OpenURL(realPath);
}
Btw if you want to prevent your app from completely freezing until the loading is done I would recommend to use a Coroutine and UnityWebRequest.Get like
public void legitOpen(string nameOfFile)
{
StartCoroutine(legitOpenRoutine(nameOfFile));
}
private IEnumerator legitOpenRoutine(string nameOfFile)
{
string realPath = Path.Combine(Application.persistentDataPath, nameOfFile + ".pdf");
if (!System.IO.File.Exists(realPath))
{
if (!System.IO.Directory.Exists(Path.Combine(Application.persistentDataPath, "PDFs"))
{
System.IO.Directory.CreateDirectory(Path.Combine(Application.persistentDataPath, "PDFs"));
}
using (var reader = new UnityWebRequest.Get(Path.Combine(Application.streamingAssetsPath, "PDFs", nameOfFile + ".pdf"))
{
yield return reader.SendWebRequest();
if (webRequest.isNetworkError)
{
Debug.Log(pages[page] + ": Error: " + webRequest.error);
return;
}
System.IO.File.WriteAllBytes(realPath, reader.bytes);
}
}
Application.OpenURL(realPath);
}
Or even completely use an async method using CopyToAsync
public void legitOpen(string nameOfFile)
{
legitOpenAsync(nameOfFile);
}
private async void legitOpenAsync(string nameOfFile)
{
var realPath = Path.Combine(Application.persistentDataPath, nameOfFile + ".pdf");
var pdfPath = Path.Combine(Application.persistentDataPath, "PDFs");
if (!System.IO.File.Exists(realPath))
{
if (!System.IO.Directory.Exists(pdfPath)
{
System.IO.Directory.CreateDirectory(pdfPath);
}
using(var sourceFile = File.Open(Path.Combine(Application.streamingAssetsPath, "PDFs", nameOfFile + ".pdf"), FileMode.Open, FileAccess.Read, FileShare.Read)
{
using(var targetFile = File.Open(realPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write))
{
await sourceFile.CopyToAsync(targetFile);
}
}
}
Application.OpenURL(realPath);
}
However
note that Application.OpenURL:
Android: Due security changes in Android 7.0 (More information), Application.OpenURL can no longer be used for opening local app files, you need to use FileProvider which allows you to share files with other applications.
and
iOS: Application.OpenURL cannot be used for opening local files.
Therefore this won't work at all
public void openPDFfromSD()
{
Application.OpenURL("/mnt/sdcard/openme.pdf");
}

Related

How to extract the .img files using c# [duplicate]

I'm trying to extract an ISO to a folder with the same name without .iso on the end.
I'm having a problem with winrar as it will not start the extract when I start up with the seach starting in the folder with the ISO.
UPDATED with answer code
private void ExtractISO(string toExtract, string folderName)
{
// reads the ISO
CDReader Reader = new CDReader(File.Open(toExtract, FileMode.Open), true);
// passes the root directory the folder name and the folder to extract
ExtractDirectory(Reader.Root, folderName /*+ Path.GetFileNameWithoutExtension(toExtract)*/ + "\\", "");
// clears reader and frees memory
Reader.Dispose();
}
private void ExtractDirectory(DiscDirectoryInfo Dinfo, string RootPath, string PathinISO)
{
if (!string.IsNullOrWhiteSpace(PathinISO))
{
PathinISO += "\\" + Dinfo.Name;
}
RootPath += "\\" + Dinfo.Name;
AppendDirectory(RootPath);
foreach (DiscDirectoryInfo dinfo in Dinfo.GetDirectories())
{
ExtractDirectory(dinfo, RootPath, PathinISO);
}
foreach (DiscFileInfo finfo in Dinfo.GetFiles())
{
using (Stream FileStr = finfo.OpenRead())
{
using (FileStream Fs = File.Create(RootPath + "\\" + finfo.Name)) // Here you can Set the BufferSize Also e.g. File.Create(RootPath + "\\" + finfo.Name, 4 * 1024)
{
FileStr.CopyTo(Fs, 4 * 1024); // Buffer Size is 4 * 1024 but you can modify it in your code as per your need
}
}
}
}
static void AppendDirectory(string path)
{
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
catch (DirectoryNotFoundException Ex)
{
AppendDirectory(Path.GetDirectoryName(path));
}
catch (PathTooLongException Ex)
{
AppendDirectory(Path.GetDirectoryName(path));
}
}
The user selects the folder to extract (.ISO) toExtract. I then use it in the Process.Start() in the background worker. That just seems to open the mounting software and doesn't extract the ISO to the desired folder name.
Thanks in advance for your help.
Or if anyone could give me a batch to extract the ISO instead and to call it from c# passing toExtract and the folder name that would be helpful too.
Thanks
If external Class Libraries are OK!
Then use SevenZipSharp or .NET DiscUtils to extract ISO's...
These two ClassLibraries can manage ISO and Extract them!
For DiscUtils you can find some codes for ISO Management [CDReader Class] at the Link I provided.
But For SevenZipSharp, Please Explore the ClassLibrary source and find the Code to Extract or Google to find it!
To get the Name of the folder just use Path.GetFileNameWithoutExtension((string)ISOFileName) which will return "ISOFile" for an iso named "ISOFile.iso". And then you can use it with your desired path.
UPDATE
Code To Extract ISO Image with DiscUtils :
using DiscUtils;
using DiscUtils.Iso9660;
void ExtractISO(string ISOName, string ExtractionPath)
{
using (FileStream ISOStream = File.Open(ISOName, FileMode.Open))
{
CDReader Reader = new CDReader(ISOStream, true, true);
ExtractDirectory(Reader.Root, ExtractionPath + Path.GetFileNameWithoutExtension(ISOName) + "\\", "");
Reader.Dispose();
}
}
void ExtractDirectory(DiscDirectoryInfo Dinfo, string RootPath, string PathinISO)
{
if (!string.IsNullOrWhiteSpace(PathinISO))
{
PathinISO += "\\" + Dinfo.Name;
}
RootPath += "\\" + Dinfo.Name;
AppendDirectory(RootPath);
foreach (DiscDirectoryInfo dinfo in Dinfo.GetDirectories())
{
ExtractDirectory(dinfo, RootPath, PathinISO);
}
foreach (DiscFileInfo finfo in Dinfo.GetFiles())
{
using (Stream FileStr = finfo.OpenRead())
{
using (FileStream Fs = File.Create(RootPath + "\\" + finfo.Name)) // Here you can Set the BufferSize Also e.g. File.Create(RootPath + "\\" + finfo.Name, 4 * 1024)
{
FileStr.CopyTo(Fs, 4 * 1024); // Buffer Size is 4 * 1024 but you can modify it in your code as per your need
}
}
}
}
static void AppendDirectory(string path)
{
try
{
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
}
catch (DirectoryNotFoundException Ex)
{
AppendDirectory(Path.GetDirectoryName(path));
}
catch (PathTooLongException Exx)
{
AppendDirectory(Path.GetDirectoryName(path));
}
}
Use It with Like This :
ExtractISO(ISOFileName, Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\");
Working! Tested By Me!
And Of Course You can always add more Optimization to the code...
This Code is Just a Basic One!
For UDF or for making Windows ISO Files after servicing(DISM) with out needs the above accepted answer is not working for me so i tried this working method with DiscUtils
using DiscUtils;
public static void ReadIsoFile(string sIsoFile, string sDestinationRootPath)
{
Stream streamIsoFile = null;
try
{
streamIsoFile = new FileStream(sIsoFile, FileMode.Open);
DiscUtils.FileSystemInfo[] fsia = FileSystemManager.DetectDefaultFileSystems(streamIsoFile);
if (fsia.Length < 1)
{
MessageBox.Show("No valid disc file system detected.");
}
else
{
DiscFileSystem dfs = fsia[0].Open(streamIsoFile);
ReadIsoFolder(dfs, #"", sDestinationRootPath);
return;
}
}
finally
{
if (streamIsoFile != null)
{
streamIsoFile.Close();
}
}
}
public static void ReadIsoFolder(DiscFileSystem cdReader, string sIsoPath, string sDestinationRootPath)
{
try
{
string[] saFiles = cdReader.GetFiles(sIsoPath);
foreach (string sFile in saFiles)
{
DiscFileInfo dfiIso = cdReader.GetFileInfo(sFile);
string sDestinationPath = Path.Combine(sDestinationRootPath, dfiIso.DirectoryName.Substring(0, dfiIso.DirectoryName.Length - 1));
if (!Directory.Exists(sDestinationPath))
{
Directory.CreateDirectory(sDestinationPath);
}
string sDestinationFile = Path.Combine(sDestinationPath, dfiIso.Name);
SparseStream streamIsoFile = cdReader.OpenFile(sFile, FileMode.Open);
FileStream fsDest = new FileStream(sDestinationFile, FileMode.Create);
byte[] baData = new byte[0x4000];
while (true)
{
int nReadCount = streamIsoFile.Read(baData, 0, baData.Length);
if (nReadCount < 1)
{
break;
}
else
{
fsDest.Write(baData, 0, nReadCount);
}
}
streamIsoFile.Close();
fsDest.Close();
}
string[] saDirectories = cdReader.GetDirectories(sIsoPath);
foreach (string sDirectory in saDirectories)
{
ReadIsoFolder(cdReader, sDirectory, sDestinationRootPath);
}
return;
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
it has extracted from a application source ISOReader but modified for my requirements
total source is available at http://www.java2s.com/Open-Source/CSharp_Free_CodeDownload/i/isoreader.zip
Try this:
string Desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Process.Start("Winrar.exe", string.Format("x {0} {1}",
Desktop + "\\test.rar",
Desktop + "\\SomeFolder"));
That would extract the file test.rar to the folder SomeFolder. You can change the .rar extention to .iso, it'll work the same.
As far as I can see in your current code, there is no command given to extract a file, and no path to the file that has to be extracted. Try this example and let me know if it works =]
P.S. If you'd like to hide the extracting screen, you can set the YourProcessInfo.WindowStyle to ProcessWindowStyle.Hidden.
I hace confrunted recently with this kind of .iso extraction issue. After trying several methods, 7zip did the job for me, you just have to make sure that the latest version of 7zip is installed on your system. Maybe it will help
try
{
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
cmd.Start();
cmd.StandardInput.WriteLine("C:");
//Console.WriteLine(cmd.StandardOutput.Read());
cmd.StandardInput.Flush();
cmd.StandardInput.WriteLine("cd C:\\\"Program Files\"\\7-Zip\\");
//Console.WriteLine(cmd.StandardOutput.ReadToEnd());
cmd.StandardInput.Flush();
cmd.StandardInput.WriteLine(string.Format("7z x -y -o{0} {1}", source, copyISOLocation.TempIsoPath));
//Console.WriteLine(cmd.StandardOutput.ReadToEnd());
cmd.StandardInput.Flush();
cmd.StandardInput.Close();
cmd.WaitForExit();
Console.WriteLine(cmd.StandardOutput.ReadToEnd());
}
catch (Exception e)
{
Console.WriteLine(e.Message + "\n" + e.StackTrace);
if (e.InnerException != null)
{
Console.WriteLine(e.InnerException.Message + "\n" + e.InnerException.StackTrace);
}
}

Downloading a directory using SSH.NET SFTP in C#

I am using Renci.SSH and C# to connect to my Unix server from a Windows machine. My code works as expected when the directory contents are only files, but if the directory contains a folder, I get this
Renci.SshNet.Common.SshException: 'Failure'
This is my code, how can I update this to also download a directory (if exists)
private static void DownloadFile(string arc, string username, string password)
{
string fullpath;
string fp;
var options = new ProgressBarOptions
{
ProgressCharacter = '.',
ProgressBarOnBottom = true
};
using (var sftp = new SftpClient(Host, username, password))
{
sftp.Connect();
fp = RemoteDir + "/" + arc;
if (sftp.Exists(fp))
fullpath = fp;
else
fullpath = SecondaryRemoteDir + d + "/" + arc;
if (sftp.Exists(fullpath))
{
var files = sftp.ListDirectory(fullpath);
foreach (var file in files)
{
if (file.Name.ToLower().Substring(0, 1) != ".")
{
Console.WriteLine("Downloading file from the server...");
Console.WriteLine();
using (var pbar = new ProgressBar(100, "Downloading " + file.Name + "....", options))
{
SftpFileAttributes att = sftp.GetAttributes(fullpath + "/" + file.Name);
var fileSize = att.Size;
var ms = new MemoryStream();
IAsyncResult asyncr = sftp.BeginDownloadFile(fullpath + "/" + file.Name, ms);
SftpDownloadAsyncResult sftpAsyncr = (SftpDownloadAsyncResult)asyncr;
int lastpct = 0;
while (!sftpAsyncr.IsCompleted)
{
int pct = (int)((long)sftpAsyncr.DownloadedBytes / fileSize) * 100;
if (pct > lastpct)
for (int i = 1; i < pct - lastpct; i++)
pbar.Tick();
}
sftp.EndDownloadFile(asyncr);
Console.WriteLine("Writing File to disk...");
Console.WriteLine();
string localFilePath = "C:\" + file.Name;
var fs = new FileStream(localFilePath, FileMode.Create, FileAccess.Write);
ms.WriteTo(fs);
fs.Close();
ms.Close();
}
}
}
}
else
{
Console.WriteLine("The arc " + arc + " does not exist");
Console.WriteLine();
Console.WriteLine("Please press any key to close this window");
Console.ReadKey();
}
}
}
BeginDownloadFile downloads a file. You cannot use it to download a folder. For that you need to download contained files one by one.
The following example uses synchronous download (DownloadFile instead of BeginDownloadFile) for simplicity. After all, you are synchronously waiting for asynchronous download to complete anyway. To implement a progress bar with synchronous download, see Displaying progress of file download in a ProgressBar with SSH.NET.
public static void DownloadDirectory(
SftpClient sftpClient, string sourceRemotePath, string destLocalPath)
{
Directory.CreateDirectory(destLocalPath);
IEnumerable<SftpFile> files = sftpClient.ListDirectory(sourceRemotePath);
foreach (SftpFile file in files)
{
if ((file.Name != ".") && (file.Name != ".."))
{
string sourceFilePath = sourceRemotePath + "/" + file.Name;
string destFilePath = Path.Combine(destLocalPath, file.Name);
if (file.IsDirectory)
{
DownloadDirectory(sftpClient, sourceFilePath, destFilePath);
}
else
{
using (Stream fileStream = File.Create(destFilePath))
{
sftpClient.DownloadFile(sourceFilePath, fileStream);
}
}
}
}
}

How to force a download of a created file to a users computer c#

I am looking to allow a person to to export journal entries into a text file. I can create a file with all the data but rather strictly saving the file somewhere specific I want to allow a user to download and save the file where they want on their computer. How to I force a download of a file after I create it with StreamWriter. I currently have the following code:
string fileName = "Journal.txt";
using (StreamWriter journalExport = new StreamWriter(fileName))
{
foreach (JournalEntryView entry in journalEnteries)
{
//write each journal entery to file/document
journalExport.WriteLine(entry.timestamp + " - " + entry.author + " (" + entry.authorRole + ")");
journalExport.WriteLine(entry.text);
journalExport.WriteLine("");
journalExport.WriteLine("");
}
}
I am also trying to put this into an ActionResult and return the file.
EDIT:
The following code is my new current code and the direction I am looking to go in, but when I use an ActionLink to call this method, i just get redirected to a new page rather than downloading the file.
string fileName = "Journal.txt";
string filepath = ConfigurationManager.AppSettings["DocumentRoot"] + "\\" + id + "\\" + fileName;
using (StreamWriter journalExport = new StreamWriter(filepath))
{
foreach (JournalEntryView entry in journalEnteries)
{
//write each journal entery to file/document
journalExport.WriteLine(entry.timestamp + " - " + entry.author + " (" + entry.authorRole + ")");
journalExport.WriteLine(entry.text);
journalExport.WriteLine("");
journalExport.WriteLine("");
}
}
byte[] fileData = System.IO.File.ReadAllBytes(filepath);
string contentType = MimeMapping.GetMimeMapping(filepath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = fileName,
Inline = true,
};
Response.AppendHeader("Content-Disposition", cd.ToString());
return File(fileData, contentType);
This might be what you are looking for:
public ActionResult GetFile()
{
...processing stuff...
return File("/files/file.pdf", "application/pdf");
//or
return File("/files/file.pdf", "application/force-download", "donwloadname.pdf");
}

Compress file - Sharing violation on path

I currentlywork on an android application, and I have to develop a function to compress files into directory.
To get all the files, I use the DirectoryInfo() and FileInfo() class and then the ZipArchive() and ZipArchiveEntry() class to create my .zip file.
The problem I have is when I open the file to compress with a FileStream to copy data into my ZipArchive entry. I got a sharing violation on path error when I use the OpenRead() function.
I already check the permissions in my Manifest and try several methods like ZipFile.CreateFromDirectory but I still have the same problem.
Thank you by advance for your help.
Here is my code :
public void Compress(DirectoryInfo directory)
{
string identifiantSC = currentSceneSelected.Id_Scene;
string typeSceneSelected = currentSceneSelected.type_Scene;
if (!Directory.Exists (Path.Combine (pathProject, "Archive"))) {
Directory.CreateDirectory (Path.Combine (pathProject, "Archive"));
}
string pathSceneDir = Path.Combine (pathProject, typeSceneSelected + "_" + identifiantSC);
string pathZipDir = Path.Combine (pathProject, "Archive");
foreach (var fileToCompress in directory.GetFiles ()) {
if (!File.Exists (Path.Combine (pathZipDir, typeSceneSelected + "_" + identifiantSC + ".zip"))) {
try {
var fileZip = new FileStream (Path.Combine (pathZipDir, typeSceneSelected + "_" + identifiantSC + ".zip"), FileMode.Create);
archive = new ZipArchive (fileZip, ZipArchiveMode.Create);
ZipArchiveEntry readmeEntry = archive.CreateEntry (fileToCompress.Name, CompressionLevel.Optimal);
FileStream originalFileStream = fileToCompress.OpenRead();
originalFileStream.CopyTo (readmeEntry.Open ());
} catch (FileLoadException e){
Console.WriteLine ("FILE LOAD EXCEPTION : " + e);
} catch (AccessViolationException e){
Console.WriteLine ("ACCESS VIOLATION EXCEPTION : " + e);
} catch (UnauthorizedAccessException e){
Console.WriteLine ("ACCESS EXCEPTION : " + e);
}
}
else {
using (var fileZip = new FileStream (Path.Combine (pathZipDir, typeSceneSelected + "_" + identifiantSC + ".zip"), FileMode.Open)) {
using (archive = new ZipArchive (fileZip, ZipArchiveMode.Update)) {
ZipArchiveEntry readmeEntry = archive.CreateEntry (fileToCompress.Name, CompressionLevel.Optimal);
FileStream originalFileStream = fileToCompress.OpenRead ();
originalFileStream.CopyTo (readmeEntry.Open ());
originalFileStream.Close ();
}
}
}
}
}

I can read and write from a txt file internal storage (documents folder) but cannot browse to that location because it doesn't exist

Alright so I've managed to read/write files programatically in C# in Xamarin Studio. And it's working on my device.
However, when I output the exact path that the file is being written to, to the console, that path doesn't even exist anywhere in the entire phone!!!!
How is that?
using System;
using System.IO;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace ToolbarSample
{
[Activity(Label = "ToolbarSample", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
string content = "Jason rules";
string filename = "file.txt";
var documents = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
// Get our button from the layout resource,
// and attach an event to it
Button button = FindViewById<Button>(Resource.Id.button);
TextView viewer = FindViewById<TextView>(Resource.Id.textView1);
if (File.Exists(documents + #"/" + filename))
{
string newContent = File.ReadAllText(documents + #"/" + filename);
if (viewer != null)
{
viewer.Text = newContent;
Console.WriteLine("File exists in: " + documents + #"/" + filename);
}
}
if (button != null)
{
button.Click += delegate
{
button.Enabled = false;
if (!Directory.Exists(documents))
{
viewer.Text = "Directory not found: " + documents;
}
else
{
Console.WriteLine("Directory exists.");
File.WriteAllText(documents + #"/" + filename, content);
if (!File.Exists(documents + #"/" + filename))
{
viewer.Text = "File not found: " + documents + #"/" + filename;
}
else
{
string newContent = File.ReadAllText(documents + #"/" + filename);
if (viewer != null)
{
viewer.Text = newContent;
Console.WriteLine("File exists in: " + documents + #"/" + filename);
}
}
}
};
}
}
}
}
The following gets outputted to the console upon successful read from internal sdcard:
Directory exists. File exists in:
/data/data/ToolbarSample.ToolbarSample/files/file.txt
But using (many different) file managers - all with root access - and hidden files being shown - I cannot navigate to that path because it does not exist. I even did a whole phone search for "file.txt" and not a single result showed up. Yet I am able to read that file whenever I open my app and click the button.
The file at the location you have specified does exist. You cannot access that location from your PC via USB and File Explorer, but you can access the location (and the file) if you use a good File Manager app like Root Explorer.
If you really want your users to be able to access these saved files, I'd suggest that you save these files to a better location so that the user can easily transfer files from their phone to the computer via USB.
It quite simple both Read/Write data from File .
public String ReadFileData()
{
var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filename = Path.Combine(path.ToString(), "loginSystem.txt");
String line;
objData = new List<UsersData>();
// Read the file and display it line by line.
StreamReader file = new StreamReader(filename);
while ((line = file.ReadLine()) != null)
{
string[] words = line.Split(',');
if (words.Length != 1)
objData.Add(new UsersData(words[0], words[1], words[2]));
}
file.Close();
return String.Empty;
}
Save data into file
private string SaveDataToSd(String FirstName, String Address, String Password)
{
var path = global::Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
var filename = Path.Combine(path.ToString(), "loginSystem.txt");
String contents = FirstName + "," + Password + "," + Address;
try
{
using (StreamWriter data_file = new StreamWriter(filename, true))
{
data_file.WriteLine(contents);
}
return contents;
}
catch (Exception ex)
{
RunOnUiThread(() =>
{
var builder = new AlertDialog.Builder(this);
builder.SetMessage(ex.InnerException + "Saving file went wrong");
builder.SetTitle("Unable to save file");
builder.Show();
});
return String.Empty;
}
}

Categories

Resources