I am trying to write in a file with Xamarin Android. Here is my code:
try
{
string r = (string)(DateFormat.Format("yyyy-MM-dd-hh-mm-ss", new Date()));
string logFileBaseName = "drLog." + r; pause();
mAccelLogFileWriter = new FileWriter(new File(STORAGE_DIR, logFileBaseName + ".accel.csv"));
mStepLogFileWriter = new FileWriter(new File(STORAGE_DIR, logFileBaseName + ".steps.csv"));
}
catch (IOException e)
{
Log.Error(TAG, "Creating and opening log files failed!", e);
e.PrintStackTrace();
throw new RuntimeException(e);
}
Knowing that I defined:
protected string STORAGE_DIR = SAMPLES_DIR + File.Separator + "dr";
protected static readonly string SAMPLES_DIR = Android.OS.Environment.ExternalStorageDirectory + File.Separator + "samples_exp";
The problem is I get this exception when I create the file mAccelLogFileWriter. This exception says:
Java.Lang.RuntimeException: java.io.FileNotFoundException: /storage/emulated/0/samples_exp/dr/drLog.2016-07-21-09-22-59.accel.csv: open failed: ENOENT (No such file or directory)
When I debug the code I find for example that: SAMPLES_DIR="/storage/emulated/0/samples_exp" While I am trying to Get the External Storage Directory (SD Card).
Can you please tell me what is wrong with my code?
Use Java.IO.File.Mkdirs
to make all the directories on your path before creating a Java.IO.FileWriter
.
string SAMPLES_DIR = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.ToString(), "samples_exp");
string STORAGE_DIR = Path.Combine(SAMPLES_DIR, "dr");
var r = DateFormat.Format("yyyy-MM-dd-hh-mm-ss", new Java.Util.Date());
var logFileBaseName = "drLog." + r;
// ~~~~
var storageDirs = new Java.IO.File(STORAGE_DIR);
storageDirs.Mkdirs();
// ~~~~
var mAccelLogFileWriter = new Java.IO.FileWriter(new Java.IO.File(STORAGE_DIR, logFileBaseName + ".accel.csv"));
var mStepLogFileWriter = new Java.IO.FileWriter(new Java.IO.File(STORAGE_DIR, logFileBaseName + ".steps.csv"));
adb shell ls -R sdcard/samples_exp
sdcard/samples_exp:
dr
sdcard/samples_exp/dr:
drLog.2016-07-21-03-50-52.accel.csv
drLog.2016-07-21-03-50-52.steps.csv