Xamarin Android下的filewriter问题

时间:2016-07-21 07:30:00

标签: android xamarin filewriter

我正在尝试用Xamarin Android写一个文件。 这是我的代码:

 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);
 }

知道我定义了:

protected string STORAGE_DIR = SAMPLES_DIR + File.Separator + "dr";
 protected static readonly string SAMPLES_DIR = Android.OS.Environment.ExternalStorageDirectory + File.Separator + "samples_exp";

问题是我在创建文件mAccelLogFileWriter时遇到此异常。 这个例外说:

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)

当我调试代码时,我发现例如:SAMPLES_DIR =“/ storage / emulated / 0 / samples_exp” 我正在尝试获取外部存储目录(SD卡)。

你能告诉我我的代码有什么问题吗?

1 个答案:

答案 0 :(得分:2)

在创建Java.IO.File.Mkdirs之前,使用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输出:

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