6 // Miguel de Icaza (miguel@ximian.com)
7 // Jim Richardson (develop@wtfo-guru.com)
8 // Dan Lewis (dihlewis@yahoo.co.uk)
9 // Ville Palo (vi64pa@kolumbus.fi)
11 // Copyright 2002 Ximian, Inc. http://www.ximian.com
12 // Copyright (C) 2001 Moonlight Enterprises, All Rights Reserved
13 // Copyright (C) 2004, 2006, 2010 Novell, Inc (http://www.novell.com)
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Collections.Generic;
37 using System.Diagnostics;
38 using System.Security;
40 using System.Runtime.InteropServices;
43 using System.Security.AccessControl;
49 public static class File
51 public static void AppendAllText (string path, string contents)
53 using (TextWriter w = new StreamWriter (path, true)) {
58 public static void AppendAllText (string path, string contents, Encoding encoding)
60 using (TextWriter w = new StreamWriter (path, true, encoding)) {
65 public static StreamWriter AppendText (string path)
67 return new StreamWriter (path, true);
70 public static void Copy (string sourceFileName, string destFileName)
72 Copy (sourceFileName, destFileName, false);
75 public static void Copy (string sourceFileName, string destFileName, bool overwrite)
79 if (sourceFileName == null)
80 throw new ArgumentNullException ("sourceFileName");
81 if (destFileName == null)
82 throw new ArgumentNullException ("destFileName");
83 if (sourceFileName.Length == 0)
84 throw new ArgumentException ("An empty file name is not valid.", "sourceFileName");
85 if (sourceFileName.Trim ().Length == 0 || sourceFileName.IndexOfAny (Path.InvalidPathChars) != -1)
86 throw new ArgumentException ("The file name is not valid.");
87 if (destFileName.Length == 0)
88 throw new ArgumentException ("An empty file name is not valid.", "destFileName");
89 if (destFileName.Trim ().Length == 0 || destFileName.IndexOfAny (Path.InvalidPathChars) != -1)
90 throw new ArgumentException ("The file name is not valid.");
92 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
94 if (!MonoIO.Exists (sourceFileName, out error))
95 throw new FileNotFoundException (Locale.GetText ("{0} does not exist", sourceFileName), sourceFileName);
96 if ((GetAttributes (sourceFileName) & FileAttributes.Directory) == FileAttributes.Directory)
97 throw new ArgumentException (Locale.GetText ("{0} is a directory", sourceFileName));
99 if (MonoIO.Exists (destFileName, out error)) {
100 if ((GetAttributes (destFileName) & FileAttributes.Directory) == FileAttributes.Directory)
101 throw new ArgumentException (Locale.GetText ("{0} is a directory", destFileName));
103 throw new IOException (Locale.GetText ("{0} already exists", destFileName));
106 string DirName = Path.GetDirectoryName (destFileName);
107 if (DirName != String.Empty && !Directory.Exists (DirName))
108 throw new DirectoryNotFoundException (Locale.GetText ("Destination directory not found: {0}",DirName));
110 if (!MonoIO.CopyFile (sourceFileName, destFileName, overwrite, out error)) {
111 string p = Locale.GetText ("{0}\" or \"{1}", sourceFileName, destFileName);
112 throw MonoIO.GetException (p, error);
116 public static FileStream Create (string path)
118 return Create (path, 8192);
121 public static FileStream Create (string path, int bufferSize)
123 return new FileStream (path, FileMode.Create, FileAccess.ReadWrite,
124 FileShare.None, bufferSize);
128 [MonoLimitation ("FileOptions are ignored")]
129 public static FileStream Create (string path, int bufferSize,
132 return Create (path, bufferSize, options, null);
135 [MonoLimitation ("FileOptions and FileSecurity are ignored")]
136 public static FileStream Create (string path, int bufferSize,
138 FileSecurity fileSecurity)
140 return new FileStream (path, FileMode.Create, FileAccess.ReadWrite,
141 FileShare.None, bufferSize, options);
145 public static StreamWriter CreateText (string path)
147 return new StreamWriter (path, false);
150 public static void Delete (string path)
152 Path.Validate (path);
153 if (Directory.Exists (path))
154 throw new UnauthorizedAccessException(Locale.GetText ("{0} is a directory", path));
156 string DirName = Path.GetDirectoryName(path);
157 if (DirName != String.Empty && !Directory.Exists (DirName))
158 throw new DirectoryNotFoundException (Locale.GetText ("Could not find a part of the path \"{0}\".", path));
160 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
164 if (!MonoIO.DeleteFile (path, out error)){
165 if (error != MonoIOError.ERROR_FILE_NOT_FOUND)
166 throw MonoIO.GetException (path, error);
170 public static bool Exists (string path)
172 // For security reasons no exceptions are
173 // thrown, only false is returned if there is
174 // any problem with the path or permissions.
175 // Minimizes what information can be
176 // discovered by using this method.
177 if (String.IsNullOrWhiteSpace (path) || path.IndexOfAny(Path.InvalidPathChars) >= 0)
180 // on Moonlight this does not throw but returns false
181 if (!SecurityManager.CheckElevatedPermissions ())
185 return MonoIO.ExistsFile (path, out error);
189 public static FileSecurity GetAccessControl (string path)
191 throw new NotImplementedException ();
194 public static FileSecurity GetAccessControl (string path, AccessControlSections includeSections)
196 throw new NotImplementedException ();
200 public static FileAttributes GetAttributes (string path)
202 Path.Validate (path);
203 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
206 FileAttributes attrs;
208 attrs = MonoIO.GetFileAttributes (path, out error);
209 if (error != MonoIOError.ERROR_SUCCESS)
210 throw MonoIO.GetException (path, error);
214 public static DateTime GetCreationTime (string path)
218 Path.Validate (path);
219 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
221 if (!MonoIO.GetFileStat (path, out stat, out error)) {
222 if (error == MonoIOError.ERROR_PATH_NOT_FOUND || error == MonoIOError.ERROR_FILE_NOT_FOUND)
223 return DefaultLocalFileTime;
225 throw new IOException (path);
227 return DateTime.FromFileTime (stat.CreationTime);
230 public static DateTime GetCreationTimeUtc (string path)
232 return GetCreationTime (path).ToUniversalTime ();
235 public static DateTime GetLastAccessTime (string path)
239 Path.Validate (path);
240 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
242 if (!MonoIO.GetFileStat (path, out stat, out error)) {
243 if (error == MonoIOError.ERROR_PATH_NOT_FOUND || error == MonoIOError.ERROR_FILE_NOT_FOUND)
244 return DefaultLocalFileTime;
246 throw new IOException (path);
248 return DateTime.FromFileTime (stat.LastAccessTime);
251 public static DateTime GetLastAccessTimeUtc (string path)
253 return GetLastAccessTime (path).ToUniversalTime ();
256 public static DateTime GetLastWriteTime (string path)
260 Path.Validate (path);
261 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
263 if (!MonoIO.GetFileStat (path, out stat, out error)) {
264 if (error == MonoIOError.ERROR_PATH_NOT_FOUND || error == MonoIOError.ERROR_FILE_NOT_FOUND)
265 return DefaultLocalFileTime;
267 throw new IOException (path);
269 return DateTime.FromFileTime (stat.LastWriteTime);
272 public static DateTime GetLastWriteTimeUtc (string path)
274 return GetLastWriteTime (path).ToUniversalTime ();
277 public static void Move (string sourceFileName, string destFileName)
279 if (sourceFileName == null)
280 throw new ArgumentNullException ("sourceFileName");
281 if (destFileName == null)
282 throw new ArgumentNullException ("destFileName");
283 if (sourceFileName.Length == 0)
284 throw new ArgumentException ("An empty file name is not valid.", "sourceFileName");
285 if (sourceFileName.Trim ().Length == 0 || sourceFileName.IndexOfAny (Path.InvalidPathChars) != -1)
286 throw new ArgumentException ("The file name is not valid.");
287 if (destFileName.Length == 0)
288 throw new ArgumentException ("An empty file name is not valid.", "destFileName");
289 if (destFileName.Trim ().Length == 0 || destFileName.IndexOfAny (Path.InvalidPathChars) != -1)
290 throw new ArgumentException ("The file name is not valid.");
292 SecurityManager.EnsureElevatedPermissions (); // this is a no-op outside moonlight
295 if (!MonoIO.Exists (sourceFileName, out error))
296 throw new FileNotFoundException (Locale.GetText ("{0} does not exist", sourceFileName), sourceFileName);
298 // Don't check for this error here to allow the runtime
299 // to check if sourceFileName and destFileName are equal.
300 // Comparing sourceFileName and destFileName is not enough.
301 //if (MonoIO.Exists (destFileName, out error))
302 // throw new IOException (Locale.GetText ("{0} already exists", destFileName));
305 DirName = Path.GetDirectoryName (destFileName);
306 if (DirName != String.Empty && !Directory.Exists (DirName))
307 throw new DirectoryNotFoundException (Locale.GetText ("Could not find a part of the path."));
309 if (!MonoIO.MoveFile (sourceFileName, destFileName, out error)) {
310 if (error == MonoIOError.ERROR_ALREADY_EXISTS)
311 throw MonoIO.GetException (error);
312 else if (error == MonoIOError.ERROR_SHARING_VIOLATION)
313 throw MonoIO.GetException (sourceFileName, error);
315 throw MonoIO.GetException (error);
319 public static FileStream Open (string path, FileMode mode)
321 return new FileStream (path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, FileShare.None);
324 public static FileStream Open (string path, FileMode mode, FileAccess access)
326 return new FileStream (path, mode, access, FileShare.None);
329 public static FileStream Open (string path, FileMode mode, FileAccess access,
332 return new FileStream (path, mode, access, share);
335 public static FileStream OpenRead (string path)
337 return new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.Read);
340 public static StreamReader OpenText (string path)
342 return new StreamReader (path);
345 public static FileStream OpenWrite (string path)
347 return new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
350 public static void Replace (string sourceFileName,
351 string destinationFileName,
352 string destinationBackupFileName)
354 Replace (sourceFileName, destinationFileName, destinationBackupFileName, false);
357 public static void Replace (string sourceFileName,
358 string destinationFileName,
359 string destinationBackupFileName,
360 bool ignoreMetadataErrors)
364 if (sourceFileName == null)
365 throw new ArgumentNullException ("sourceFileName");
366 if (destinationFileName == null)
367 throw new ArgumentNullException ("destinationFileName");
368 if (sourceFileName.Trim ().Length == 0 || sourceFileName.IndexOfAny (Path.InvalidPathChars) != -1)
369 throw new ArgumentException ("sourceFileName");
370 if (destinationFileName.Trim ().Length == 0 || destinationFileName.IndexOfAny (Path.InvalidPathChars) != -1)
371 throw new ArgumentException ("destinationFileName");
373 string fullSource = Path.GetFullPath (sourceFileName);
374 string fullDest = Path.GetFullPath (destinationFileName);
375 if (MonoIO.ExistsDirectory (fullSource, out error))
376 throw new IOException (Locale.GetText ("{0} is a directory", sourceFileName));
377 if (MonoIO.ExistsDirectory (fullDest, out error))
378 throw new IOException (Locale.GetText ("{0} is a directory", destinationFileName));
380 if (!Exists (fullSource))
381 throw new FileNotFoundException (Locale.GetText ("{0} does not exist", sourceFileName),
383 if (!Exists (fullDest))
384 throw new FileNotFoundException (Locale.GetText ("{0} does not exist", destinationFileName),
385 destinationFileName);
386 if (fullSource == fullDest)
387 throw new IOException (Locale.GetText ("Source and destination arguments are the same file."));
389 string fullBackup = null;
390 if (destinationBackupFileName != null) {
391 if (destinationBackupFileName.Trim ().Length == 0 ||
392 destinationBackupFileName.IndexOfAny (Path.InvalidPathChars) != -1)
393 throw new ArgumentException ("destinationBackupFileName");
395 fullBackup = Path.GetFullPath (destinationBackupFileName);
396 if (MonoIO.ExistsDirectory (fullBackup, out error))
397 throw new IOException (Locale.GetText ("{0} is a directory", destinationBackupFileName));
398 if (fullSource == fullBackup)
399 throw new IOException (Locale.GetText ("Source and backup arguments are the same file."));
400 if (fullDest == fullBackup)
401 throw new IOException (Locale.GetText (
402 "Destination and backup arguments are the same file."));
405 if (!MonoIO.ReplaceFile (fullSource, fullDest, fullBackup,
406 ignoreMetadataErrors, out error)) {
407 throw MonoIO.GetException (error);
412 public static void SetAccessControl (string path,
413 FileSecurity fileSecurity)
415 throw new NotImplementedException ();
419 public static void SetAttributes (string path,
420 FileAttributes fileAttributes)
423 Path.Validate (path);
425 if (!MonoIO.SetFileAttributes (path, fileAttributes, out error))
426 throw MonoIO.GetException (path, error);
429 public static void SetCreationTime (string path, DateTime creationTime)
432 Path.Validate (path);
433 if (!MonoIO.Exists (path, out error))
434 throw MonoIO.GetException (path, error);
435 if (!MonoIO.SetCreationTime (path, creationTime, out error))
436 throw MonoIO.GetException (path, error);
439 public static void SetCreationTimeUtc (string path, DateTime creationTimeUtc)
441 SetCreationTime (path, creationTimeUtc.ToLocalTime ());
444 public static void SetLastAccessTime (string path, DateTime lastAccessTime)
447 Path.Validate (path);
448 if (!MonoIO.Exists (path, out error))
449 throw MonoIO.GetException (path, error);
450 if (!MonoIO.SetLastAccessTime (path, lastAccessTime, out error))
451 throw MonoIO.GetException (path, error);
454 public static void SetLastAccessTimeUtc (string path, DateTime lastAccessTimeUtc)
456 SetLastAccessTime (path, lastAccessTimeUtc.ToLocalTime ());
459 public static void SetLastWriteTime (string path,
460 DateTime lastWriteTime)
463 Path.Validate (path);
464 if (!MonoIO.Exists (path, out error))
465 throw MonoIO.GetException (path, error);
466 if (!MonoIO.SetLastWriteTime (path, lastWriteTime, out error))
467 throw MonoIO.GetException (path, error);
470 public static void SetLastWriteTimeUtc (string path,
471 DateTime lastWriteTimeUtc)
473 SetLastWriteTime (path, lastWriteTimeUtc.ToLocalTime ());
477 // The documentation for this method is most likely wrong, it
478 // talks about doing a "binary read", but the remarks say
479 // that this "detects the encoding".
481 // This can not detect and do anything useful with the encoding
482 // since the result is a byte [] not a char [].
484 public static byte [] ReadAllBytes (string path)
486 using (FileStream s = OpenRead (path)) {
487 long size = s.Length;
488 // limited to 2GB according to http://msdn.microsoft.com/en-us/library/system.io.file.readallbytes.aspx
489 if (size > Int32.MaxValue)
490 throw new IOException ("Reading more than 2GB with this call is not supported");
493 int count = (int) size;
494 byte [] result = new byte [size];
496 int n = s.Read (result, pos, count);
498 throw new IOException ("Unexpected end of stream");
506 public static string [] ReadAllLines (string path)
508 using (StreamReader reader = File.OpenText (path)) {
509 return ReadAllLines (reader);
513 public static string [] ReadAllLines (string path, Encoding encoding)
515 using (StreamReader reader = new StreamReader (path, encoding)) {
516 return ReadAllLines (reader);
520 static string [] ReadAllLines (StreamReader reader)
522 List<string> list = new List<string> ();
523 while (!reader.EndOfStream)
524 list.Add (reader.ReadLine ());
525 return list.ToArray ();
528 public static string ReadAllText (string path)
530 using (StreamReader sr = new StreamReader (path)) {
531 return sr.ReadToEnd ();
535 public static string ReadAllText (string path, Encoding encoding)
537 using (StreamReader sr = new StreamReader (path, encoding)) {
538 return sr.ReadToEnd ();
542 public static void WriteAllBytes (string path, byte [] bytes)
544 using (Stream stream = File.Create (path)) {
545 stream.Write (bytes, 0, bytes.Length);
549 public static void WriteAllLines (string path, string [] contents)
551 using (StreamWriter writer = new StreamWriter (path)) {
552 WriteAllLines (writer, contents);
556 public static void WriteAllLines (string path, string [] contents, Encoding encoding)
558 using (StreamWriter writer = new StreamWriter (path, false, encoding)) {
559 WriteAllLines (writer, contents);
563 static void WriteAllLines (StreamWriter writer, string [] contents)
565 foreach (string line in contents)
566 writer.WriteLine (line);
569 public static void WriteAllText (string path, string contents)
571 WriteAllText (path, contents, Encoding.UTF8Unmarked);
574 public static void WriteAllText (string path, string contents, Encoding encoding)
576 using (StreamWriter sw = new StreamWriter (path, false, encoding)) {
581 static DateTime? defaultLocalFileTime;
582 static DateTime DefaultLocalFileTime {
584 if (defaultLocalFileTime == null)
585 defaultLocalFileTime = new DateTime (1601, 1, 1).ToLocalTime ();
587 return defaultLocalFileTime.Value;
592 [MonoLimitation ("File encryption isn't supported (even on NTFS).")]
593 public static void Encrypt (string path)
595 // MS.NET support this only on NTFS file systems, i.e. it's a file-system (not a framework) feature.
596 // otherwise it throws a NotSupportedException (or a PlatformNotSupportedException on older OS).
597 // we throw the same (instead of a NotImplementedException) because most code should already be
598 // handling this exception to work properly.
599 throw new NotSupportedException (Locale.GetText ("File encryption isn't supported on any file system."));
602 [MonoLimitation ("File encryption isn't supported (even on NTFS).")]
603 public static void Decrypt (string path)
605 // MS.NET support this only on NTFS file systems, i.e. it's a file-system (not a framework) feature.
606 // otherwise it throws a NotSupportedException (or a PlatformNotSupportedException on older OS).
607 // we throw the same (instead of a NotImplementedException) because most code should already be
608 // handling this exception to work properly.
609 throw new NotSupportedException (Locale.GetText ("File encryption isn't supported on any file system."));
612 #if MOONLIGHT || NET_4_0
613 public static IEnumerable<string> ReadLines (string path)
615 using (StreamReader reader = File.OpenText (path)) {
616 return ReadLines (reader);
620 public static IEnumerable<string> ReadLines (string path, Encoding encoding)
622 using (StreamReader reader = new StreamReader (path, encoding)) {
623 return ReadLines (reader);
627 // refactored in order to avoid compiler-generated names for Moonlight tools
628 static IEnumerable<string> ReadLines (StreamReader reader)
631 while ((s = reader.ReadLine ()) != null)
635 public static void AppendAllLines (string path, IEnumerable<string> contents)
637 Path.Validate (path);
639 if (contents == null)
642 using (TextWriter w = new StreamWriter (path, true)) {
643 foreach (var line in contents)
648 public static void AppendAllLines (string path, IEnumerable<string> contents, Encoding encoding)
650 Path.Validate (path);
652 if (contents == null)
655 using (TextWriter w = new StreamWriter (path, true, encoding)) {
656 foreach (var line in contents)
661 public static void WriteAllLines (string path, IEnumerable<string> contents)
663 Path.Validate (path);
665 if (contents == null)
668 using (TextWriter w = new StreamWriter (path, false)) {
669 foreach (var line in contents)
674 public static void WriteAllLines (string path, IEnumerable<string> contents, Encoding encoding)
676 Path.Validate (path);
678 if (contents == null)
681 using (TextWriter w = new StreamWriter (path, false, encoding)) {
682 foreach (var line in contents)