The Labs \ Source Viewer \ SSCLI \ System.IO \ FileInfo

  1. // ==++==
  2. //
  3. //
  4. // Copyright (c) 2006 Microsoft Corporation. All rights reserved.
  5. //
  6. // The use and distribution terms for this software are contained in the file
  7. // named license.txt, which can be found in the root of this distribution.
  8. // By using this software in any fashion, you are agreeing to be bound by the
  9. // terms of this license.
  10. //
  11. // You must not remove this notice, or any other, from this software.
  12. //
  13. //
  14. // ==--==
  15. /*============================================================
  16. **
  17. ** Class:  File
  18. **
  19. **
  20. ** Purpose: A collection of methods for manipulating Files.
  21. **
  22. **          April 09,2000 (some design refactorization)
  23. **
  24. ===========================================================*/
  25. using System;
  26. using System.Security.Permissions;
  27. using PermissionSet = System.Security.PermissionSet;
  28. using Win32Native = Microsoft.Win32.Win32Native;
  29. using System.Runtime.InteropServices;
  30. using System.Text;
  31. using System.Runtime.Serialization;
  32. using System.Globalization;
  33. using System.Runtime.Versioning;
  34. namespace System.IO
  35. {
  36.     // Class for creating FileStream objects, and some basic file management
  37.     // routines such as Delete, etc.
  38.     [Serializable()]
  39.     [ComVisible(true)]
  40.     public sealed class FileInfo : FileSystemInfo
  41.     {
  42.         private string _name;
  43.        
  44.         [ResourceExposure(ResourceScope.Machine)]
  45.         [ResourceConsumption(ResourceScope.Machine)]
  46.         public FileInfo(string fileName)
  47.         {
  48.             if (fileName == null)
  49.                 throw new ArgumentNullException("fileName");
  50.            
  51.             OriginalPath = fileName;
  52.             // Must fully qualify the path for the security check
  53.             string fullPath = Path.GetFullPathInternal(fileName);
  54.             new FileIOPermission(FileIOPermissionAccess.Read, new string[] {fullPath}, false, false).Demand();
  55.            
  56.             _name = Path.GetFileName(fileName);
  57.             FullPath = fullPath;
  58.         }
  59.        
  60.         private FileInfo(SerializationInfo info, StreamingContext context) : base(info, context)
  61.         {
  62.             new FileIOPermission(FileIOPermissionAccess.Read, new string[] {FullPath}, false, false).Demand();
  63.             _name = Path.GetFileName(OriginalPath);
  64.         }
  65.        
  66.         internal FileInfo(string fullPath, bool ignoreThis)
  67.         {
  68.             BCLDebug.Assert(Path.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!");
  69.             _name = Path.GetFileName(fullPath);
  70.             OriginalPath = _name;
  71.             FullPath = fullPath;
  72.         }
  73.        
  74.         public override string Name {
  75.             get { return _name; }
  76.         }
  77.        
  78.        
  79.         public long Length {
  80.             get {
  81.                 if (_dataInitialised == -1)
  82.                     Refresh();
  83.                
  84.                 if (_dataInitialised != 0)
  85.                     // Refresh was unable to initialise the data
  86.                     __Error.WinIOError(_dataInitialised, OriginalPath);
  87.                
  88.                 if ((_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) != 0)
  89.                     __Error.WinIOError(Win32Native.ERROR_FILE_NOT_FOUND, OriginalPath);
  90.                
  91.                 return ((long)_data.fileSizeHigh) << 32 | ((long)_data.fileSizeLow & 4294967295ul);
  92.             }
  93.         }
  94.        
  95. /* Returns the name of the directory that the file is in */       
  96.         public string DirectoryName {
  97.             get {
  98.                 string directoryName = Path.GetDirectoryName(FullPath);
  99.                 if (directoryName != null)
  100.                     new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new string[] {directoryName}, false, false).Demand();
  101.                 return directoryName;
  102.             }
  103.         }
  104.        
  105. /* Creates an instance of the the parent directory */       
  106.         public DirectoryInfo Directory {
  107.             [ResourceExposure(ResourceScope.Machine)]
  108.             [ResourceConsumption(ResourceScope.Machine)]
  109.             get {
  110.                 string dirName = DirectoryName;
  111.                 if (dirName == null)
  112.                     return null;
  113.                 return new DirectoryInfo(dirName);
  114.             }
  115.         }
  116.        
  117.         public bool IsReadOnly {
  118.             get { return (Attributes & FileAttributes.ReadOnly) != 0; }
  119.             set {
  120.                 if (value)
  121.                     Attributes |= FileAttributes.ReadOnly;
  122.                 else
  123.                     Attributes &= ~FileAttributes.ReadOnly;
  124.             }
  125.         }
  126.        
  127.        
  128.         [ResourceExposure(ResourceScope.Machine)]
  129.         [ResourceConsumption(ResourceScope.Machine)]
  130.         public StreamReader OpenText()
  131.         {
  132.             return new StreamReader(FullPath, Encoding.UTF8, true, StreamReader.DefaultBufferSize);
  133.         }
  134.        
  135.         [ResourceExposure(ResourceScope.Machine)]
  136.         [ResourceConsumption(ResourceScope.Machine)]
  137.         public StreamWriter CreateText()
  138.         {
  139.             return new StreamWriter(FullPath, false);
  140.         }
  141.        
  142.        
  143.         [ResourceExposure(ResourceScope.Machine)]
  144.         [ResourceConsumption(ResourceScope.Machine)]
  145.         public StreamWriter AppendText()
  146.         {
  147.             return new StreamWriter(FullPath, true);
  148.         }
  149.        
  150.        
  151.         // Copies an existing file to a new file. An exception is raised if the
  152.         // destination file already exists. Use the
  153.         // Copy(String, String, boolean) method to allow
  154.         // overwriting an existing file.
  155.         //
  156.         // The caller must have certain FileIOPermissions. The caller must have
  157.         // Read permission to sourceFileName
  158.         // and Write permissions to destFileName.
  159.         //
  160.         [ResourceExposure(ResourceScope.Machine)]
  161.         [ResourceConsumption(ResourceScope.Machine)]
  162.         public FileInfo CopyTo(string destFileName)
  163.         {
  164.             return CopyTo(destFileName, false);
  165.         }
  166.        
  167.        
  168.         // Copies an existing file to a new file. If overwrite is
  169.         // false, then an IOException is thrown if the destination file
  170.         // already exists. If overwrite is true, the file is
  171.         // overwritten.
  172.         //
  173.         // The caller must have certain FileIOPermissions. The caller must have
  174.         // Read permission to sourceFileName and Create
  175.         // and Write permissions to destFileName.
  176.         //
  177.         [ResourceExposure(ResourceScope.Machine)]
  178.         [ResourceConsumption(ResourceScope.Machine)]
  179.         public FileInfo CopyTo(string destFileName, bool overwrite)
  180.         {
  181.             destFileName = File.InternalCopy(FullPath, destFileName, overwrite);
  182.             return new FileInfo(destFileName, false);
  183.         }
  184.        
  185.         [ResourceExposure(ResourceScope.None)]
  186.         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
  187.         public FileStream Create()
  188.         {
  189.             return File.Create(FullPath);
  190.         }
  191.        
  192.         // Deletes a file. The file specified by the designated path is deleted.
  193.         // If the file does not exist, Delete succeeds without throwing
  194.         // an exception.
  195.         //
  196.         // On NT, Delete will fail for a file that is open for normal I/O
  197.         // or a file that is memory mapped. On Win95, the file will be
  198.         // deleted irregardless of whether the file is being used.
  199.         //
  200.         // Your application must have Delete permission to the target file.
  201.         //
  202.         [ResourceExposure(ResourceScope.None)]
  203.         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
  204.         public override void Delete()
  205.         {
  206.             // For security check, path should be resolved to an absolute path.
  207.             new FileIOPermission(FileIOPermissionAccess.Write, new string[] {FullPath}, false, false).Demand();
  208.            
  209.             if (Environment.IsWin9X() && System.IO.Directory.InternalExists(FullPath))
  210.                 // Win9x fails silently for directories
  211.                 throw new UnauthorizedAccessException(String.Format(CultureInfo.CurrentCulture, Environment.GetResourceString("UnauthorizedAccess_IODenied_Path"), OriginalPath));
  212.            
  213.             bool r = Win32Native.DeleteFile(FullPath);
  214.             if (!r) {
  215.                 int hr = Marshal.GetLastWin32Error();
  216.                 if (hr == Win32Native.ERROR_FILE_NOT_FOUND)
  217.                     return;
  218.                 else
  219.                     __Error.WinIOError(hr, OriginalPath);
  220.             }
  221.         }
  222.        
  223.         [ComVisible(false)]
  224.         [ResourceExposure(ResourceScope.None)]
  225.         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
  226.         public void Decrypt()
  227.         {
  228.             File.Decrypt(FullPath);
  229.         }
  230.        
  231.         [ComVisible(false)]
  232.         [ResourceExposure(ResourceScope.None)]
  233.         [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
  234.         public void Encrypt()
  235.         {
  236.             File.Encrypt(FullPath);
  237.         }
  238.        
  239.         // Tests if the given file exists. The result is true if the file
  240.         // given by the specified path exists; otherwise, the result is
  241.         // false.
  242.         //
  243.         // Your application must have Read permission for the target directory.
  244.         public override bool Exists {
  245.             get {
  246.                 try {
  247.                     if (_dataInitialised == -1)
  248.                         Refresh();
  249.                     if (_dataInitialised != 0) {
  250.                         // Refresh was unable to initialise the data.
  251.                         // We should normally be throwing an exception here,
  252.                         // but Exists is supposed to return true or false.
  253.                         return false;
  254.                     }
  255.                     return (_data.fileAttributes & Win32Native.FILE_ATTRIBUTE_DIRECTORY) == 0;
  256.                 }
  257.                 catch {
  258.                     return false;
  259.                 }
  260.             }
  261.         }
  262.        
  263.        
  264.        
  265.        
  266.         // User must explicitly specify opening a new file or appending to one.
  267.         [ResourceExposure(ResourceScope.Machine)]
  268.         [ResourceConsumption(ResourceScope.Machine)]
  269.         public FileStream Open(FileMode mode)
  270.         {
  271.             return Open(mode, FileAccess.ReadWrite, FileShare.None);
  272.         }
  273.        
  274.        
  275.         [ResourceExposure(ResourceScope.Machine)]
  276.         [ResourceConsumption(ResourceScope.Machine)]
  277.         public FileStream Open(FileMode mode, FileAccess access)
  278.         {
  279.             return Open(mode, access, FileShare.None);
  280.         }
  281.        
  282.        
  283.         [ResourceExposure(ResourceScope.Machine)]
  284.         [ResourceConsumption(ResourceScope.Machine)]
  285.         public FileStream Open(FileMode mode, FileAccess access, FileShare share)
  286.         {
  287.             return new FileStream(FullPath, mode, access, share);
  288.         }
  289.        
  290.        
  291.        
  292.         [ResourceExposure(ResourceScope.Machine)]
  293.         [ResourceConsumption(ResourceScope.Machine)]
  294.         public FileStream OpenRead()
  295.         {
  296.             return new FileStream(FullPath, FileMode.Open, FileAccess.Read, FileShare.Read);
  297.         }
  298.        
  299.        
  300.         [ResourceExposure(ResourceScope.Machine)]
  301.         [ResourceConsumption(ResourceScope.Machine)]
  302.         public FileStream OpenWrite()
  303.         {
  304.             return new FileStream(FullPath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None);
  305.         }
  306.        
  307.        
  308.        
  309.        
  310.        
  311.        
  312.         // Moves a given file to a new location and potentially a new file name.
  313.         // This method does work across volumes.
  314.         //
  315.         // The caller must have certain FileIOPermissions. The caller must
  316.         // have Read and Write permission to
  317.         // sourceFileName and Write
  318.         // permissions to destFileName.
  319.         //
  320.         [ResourceExposure(ResourceScope.Machine)]
  321.         [ResourceConsumption(ResourceScope.Machine)]
  322.         public void MoveTo(string destFileName)
  323.         {
  324.             if (destFileName == null)
  325.                 throw new ArgumentNullException("destFileName");
  326.             if (destFileName.Length == 0)
  327.                 throw new ArgumentException(Environment.GetResourceString("Argument_EmptyFileName"), "destFileName");
  328.            
  329.             new FileIOPermission(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, new string[] {FullPath}, false, false).Demand();
  330.             string fullDestFileName = Path.GetFullPathInternal(destFileName);
  331.             new FileIOPermission(FileIOPermissionAccess.Write, new string[] {fullDestFileName}, false, false).Demand();
  332.            
  333.             if (!Win32Native.MoveFile(FullPath, fullDestFileName))
  334.                 __Error.WinIOError();
  335.             FullPath = fullDestFileName;
  336.             OriginalPath = destFileName;
  337.             _name = Path.GetFileName(fullDestFileName);
  338.            
  339.             // Flush any cached information about the file.
  340.             _dataInitialised = -1;
  341.         }
  342.        
  343.         [ComVisible(false)]
  344.         [ResourceExposure(ResourceScope.Machine)]
  345.         [ResourceConsumption(ResourceScope.Machine)]
  346.         public FileInfo Replace(string destinationFileName, string destinationBackupFileName)
  347.         {
  348.             return Replace(destinationFileName, destinationBackupFileName, false);
  349.         }
  350.        
  351.         [ComVisible(false)]
  352.         [ResourceExposure(ResourceScope.Machine)]
  353.         [ResourceConsumption(ResourceScope.Machine)]
  354.         public FileInfo Replace(string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors)
  355.         {
  356.             File.Replace(FullPath, destinationFileName, destinationBackupFileName, ignoreMetadataErrors);
  357.             return new FileInfo(destinationFileName);
  358.         }
  359.        
  360.         // Returns the original path
  361.         public override string ToString()
  362.         {
  363.             return OriginalPath;
  364.         }
  365.     }
  366. }

Developer Fusion