File.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. using System;
  5. using System.Diagnostics;
  6. using System.Security;
  7. using System.IO;
  8. namespace Internal.IO
  9. {
  10. //
  11. // Subsetted clone of System.IO.File for internal runtime use.
  12. // Keep in sync with https://github.com/dotnet/corefx/tree/master/src/System.IO.FileSystem.
  13. //
  14. internal static partial class File
  15. {
  16. // Tests if a file exists. The result is true if the file
  17. // given by the specified path exists; otherwise, the result is
  18. // false. Note that if path describes a directory,
  19. // Exists will return true.
  20. public static bool Exists(string path)
  21. {
  22. try
  23. {
  24. if (path == null)
  25. return false;
  26. if (path.Length == 0)
  27. return false;
  28. path = Path.GetFullPath(path);
  29. // After normalizing, check whether path ends in directory separator.
  30. // Otherwise, FillAttributeInfo removes it and we may return a false positive.
  31. // GetFullPath should never return null
  32. Debug.Assert(path != null, "File.Exists: GetFullPath returned null");
  33. if (path.Length > 0 && PathInternal.IsDirectorySeparator(path[path.Length - 1]))
  34. {
  35. return false;
  36. }
  37. return InternalExists(path);
  38. }
  39. catch (ArgumentException) { }
  40. catch (NotSupportedException) { } // Security can throw this on ":"
  41. catch (SecurityException) { }
  42. catch (IOException) { }
  43. catch (UnauthorizedAccessException) { }
  44. return false;
  45. }
  46. public static byte[] ReadAllBytes(string path)
  47. {
  48. // bufferSize == 1 used to avoid unnecessary buffer in FileStream
  49. using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 1))
  50. {
  51. long fileLength = fs.Length;
  52. if (fileLength > int.MaxValue)
  53. throw new IOException(SR.IO_FileTooLong2GB);
  54. int index = 0;
  55. int count = (int)fileLength;
  56. byte[] bytes = new byte[count];
  57. while (count > 0)
  58. {
  59. int n = fs.Read(bytes, index, count);
  60. if (n == 0)
  61. throw Error.GetEndOfFile();
  62. index += n;
  63. count -= n;
  64. }
  65. return bytes;
  66. }
  67. }
  68. }
  69. }