mezoni
mezoni

Reputation: 11218

How to change file date attributes (at least modified date) using "dart:io"?

I want change the modificitation date and time of the file.

How I can do this in Dart platform?

Example from the .NET Framework, C# language.

File.SetLastWriteTime(path, DateTime.Now);

I'm sure it's possible.

I just don't know how to do it in standard way in such a wonderful platform as the Dart.

It is impossible in Dart

Upvotes: 2

Views: 787

Answers (3)

Stefan
Stefan

Reputation: 766

As of Feb 9, 2017, you can set a file modified date like this:

var myFile = await File('foo.bar').openWrite();
await myFile.setLastModified(DateTime.now());

Upvotes: 0

Jim Gomes
Jim Gomes

Reputation: 824

Calling out to system processes seems like a serious hack. Here are two functions that uses only Dart APIs, and is not platform dependent. One is synchronous, and the other asynchronous. Use whichever version suits your needs.

void touchFileSync(File file) {
  final touchfile = file.openSync(mode: FileMode.append);
  touchfile.flushSync();
  touchfile.closeSync();
}

Future<void> touchFile(File file) async {
  final touchfile = await file.open(mode: FileMode.append);
  await touchfile.flush();
  await touchfile.close();
}

This will update the last modified time.

Upvotes: 2

ovangle
ovangle

Reputation: 2031

The first method that comes to mind would be to just call touch using Process.

eg.

import 'dart:io';

Future touchFile(File f) {
  return Process.run("touch", [f.path]);
}

void main() {
   var f = new File('example');
   print(f.statSync().changed);
   touchFile(f).then((_) {
     print(f.statSync().changed);
   });
}

The equivalent code for people who are chained to windows would be

Future touchFile(File f) {
  return Process.run("copy", ["\b", f.path, "+,,"]);
}

See this question

Upvotes: 4

Related Questions