Imported Upstream version 4.0.0~alpha1

Former-commit-id: 806294f5ded97629b74c85c09952f2a74fe182d9
This commit is contained in:
Jo Shields
2015-04-07 09:35:12 +01:00
parent 283343f570
commit 3c1f479b9d
22469 changed files with 2931443 additions and 869343 deletions

View File

@@ -0,0 +1,107 @@
using System;
using System.Diagnostics.Contracts;
using System.Runtime.Versioning;
using System.Text;
namespace System.IO
{
// An iterator that returns a single line at-a-time from a given file.
//
// Known issues which cannot be changed to remain compatible with 4.0:
//
// - The underlying StreamReader is allocated upfront for the IEnumerable<T> before
// GetEnumerator has even been called. While this is good in that exceptions such as
// DirectoryNotFoundException and FileNotFoundException are thrown directly by
// File.ReadLines (which the user probably expects), it also means that the reader
// will be leaked if the user never actually foreach's over the enumerable (and hence
// calls Dispose on at least one IEnumerator<T> instance).
//
// - Reading to the end of the IEnumerator<T> disposes it. This means that Dispose
// is called twice in a normal foreach construct.
//
// - IEnumerator<T> instances from the same IEnumerable<T> party on the same underlying
// reader (Dev10 Bugs 904764).
//
internal class ReadLinesIterator : Iterator<string>
{
private readonly string _path;
private readonly Encoding _encoding;
private StreamReader _reader;
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private ReadLinesIterator(string path, Encoding encoding, StreamReader reader)
{
Contract.Requires(path != null);
Contract.Requires(path.Length > 0);
Contract.Requires(encoding != null);
Contract.Requires(reader != null);
_path = path;
_encoding = encoding;
_reader = reader;
}
public override bool MoveNext()
{
if (this._reader != null)
{
this.current = _reader.ReadLine();
if (this.current != null)
return true;
// To maintain 4.0 behavior we Dispose
// after reading to the end of the reader.
Dispose();
}
return false;
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecuritySafeCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
protected override Iterator<string> Clone()
{
// NOTE: To maintain the same behavior with the previous yield-based
// iterator in 4.0, we have all the IEnumerator<T> instances share the same
// underlying reader. If we have already been disposed, _reader will be null,
// which will cause CreateIterator to simply new up a new instance to start up
// a new iteration. Dev10 Bugs 904764 has been filed to fix this in next side-
// by-side release.
return CreateIterator(_path, _encoding, _reader);
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
{
if (_reader != null)
{
_reader.Dispose();
}
}
}
finally
{
_reader = null;
base.Dispose(disposing);
}
}
internal static ReadLinesIterator CreateIterator(string path, Encoding encoding)
{
return CreateIterator(path, encoding, (StreamReader)null);
}
#if FEATURE_LEGACYNETCFIOSECURITY
[System.Security.SecuritySafeCritical]
#endif //FEATURE_LEGACYNETCFIOSECURITY
private static ReadLinesIterator CreateIterator(string path, Encoding encoding, StreamReader reader)
{
return new ReadLinesIterator(path, encoding, reader ?? new StreamReader(path, encoding));
}
}
}

View File

@@ -0,0 +1,291 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** <OWNER>[....]</OWNER>
**
** Class: ConsoleStream
**
**
** Purpose: Exposes a separate Stream for Console IO and
** handles WinCE appropriately. Also keeps us from using the
** ThreadPool for all Console output.
**
**
===========================================================*/
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
using System.Diagnostics.Contracts;
namespace System.IO {
internal sealed class __ConsoleStream : Stream
{
// We know that if we are using console APIs rather than file APIs, then the encoding
// is Encoding.Unicode implying 2 bytes per character:
const int BytesPerWChar = 2;
[System.Security.SecurityCritical] // auto-generated
private SafeFileHandle _handle;
private bool _canRead;
private bool _canWrite;
private bool _useFileAPIs;
private bool _isPipe; // When reading from pipes, we need to properly handle EOF cases.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
internal __ConsoleStream(SafeFileHandle handle, FileAccess access, bool useFileAPIs)
{
Contract.Assert(handle != null && !handle.IsInvalid, "__ConsoleStream expects a valid handle!");
_handle = handle;
_canRead = ( (access & FileAccess.Read) == FileAccess.Read );
_canWrite = ( (access & FileAccess.Write) == FileAccess.Write);
_useFileAPIs = useFileAPIs;
_isPipe = Win32Native.GetFileType(handle) == Win32Native.FILE_TYPE_PIPE;
}
public override bool CanRead {
[Pure]
get { return _canRead; }
}
public override bool CanWrite {
[Pure]
get { return _canWrite; }
}
public override bool CanSeek {
[Pure]
get { return false; }
}
public override long Length {
get {
__Error.SeekNotSupported();
return 0; // compiler appeasement
}
}
public override long Position {
get {
__Error.SeekNotSupported();
return 0; // compiler appeasement
}
set {
__Error.SeekNotSupported();
}
}
[System.Security.SecuritySafeCritical] // auto-generated
protected override void Dispose(bool disposing)
{
// We're probably better off not closing the OS handle here. First,
// we allow a program to get multiple instances of __ConsoleStreams
// around the same OS handle, so closing one handle would invalidate
// them all. Additionally, we want a second AppDomain to be able to
// write to stdout if a second AppDomain quits.
if (_handle != null) {
_handle = null;
}
_canRead = false;
_canWrite = false;
base.Dispose(disposing);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void Flush()
{
if (_handle == null) __Error.FileNotOpen();
if (!CanWrite) __Error.WriteNotSupported();
}
public override void SetLength(long value)
{
__Error.SeekNotSupported();
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
public override int Read([In, Out] byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException((offset < 0 ? "offset" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_canRead) __Error.ReadNotSupported();
int bytesRead;
int errCode = ReadFileNative(_handle, buffer, offset, count, _useFileAPIs, _isPipe, out bytesRead);
if (Win32Native.ERROR_SUCCESS != errCode)
__Error.WinIOError(errCode, String.Empty);
return bytesRead;
}
public override long Seek(long offset, SeekOrigin origin) {
__Error.SeekNotSupported();
return 0; // compiler appeasement
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
public override void Write(byte[] buffer, int offset, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer");
if (offset < 0 || count < 0)
throw new ArgumentOutOfRangeException((offset < 0 ? "offset" : "count"), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - offset < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
if (!_canWrite) __Error.WriteNotSupported();
int errCode = WriteFileNative(_handle, buffer, offset, count, _useFileAPIs);
if (Win32Native.ERROR_SUCCESS != errCode)
__Error.WinIOError(errCode, String.Empty);
return;
}
// P/Invoke wrappers for writing to and from a file, nearly identical
// to the ones on FileStream. These are duplicated to save startup/hello
// world working set.
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
private unsafe static int ReadFileNative(SafeFileHandle hFile, byte[] bytes, int offset, int count, bool useFileAPIs, bool isPipe, out int bytesRead) {
Contract.Requires(offset >= 0, "offset >= 0");
Contract.Requires(count >= 0, "count >= 0");
Contract.Requires(bytes != null, "bytes != null");
// Don't corrupt memory when multiple threads are erroneously writing
// to this stream simultaneously.
if (bytes.Length - offset < count)
throw new IndexOutOfRangeException(Environment.GetResourceString("IndexOutOfRange_IORaceCondition"));
Contract.EndContractBlock();
// You can't use the fixed statement on an array of length 0.
if (bytes.Length == 0) {
bytesRead = 0;
return Win32Native.ERROR_SUCCESS;
}
// First, wait bytes to become available. This is preferable to letting ReadFile block,
// since ReadFile is not abortable (via Thread.Abort), while WaitForAvailableConsoleInput is.
#if !FEATURE_CORESYSTEM // CoreSystem isn't signaling stdin when input is available so we can't block on it
WaitForAvailableConsoleInput(hFile, isPipe);
#endif
bool readSuccess;
#if !FEATURE_PAL
if (useFileAPIs) {
#endif // !FEATURE_PAL
fixed (byte* p = bytes) {
readSuccess = (0 != Win32Native.ReadFile(hFile, p + offset, count, out bytesRead, IntPtr.Zero));
}
#if !FEATURE_PAL
} else {
fixed (byte* p = bytes) {
int charsRead;
readSuccess = Win32Native.ReadConsoleW(hFile, p + offset, count / BytesPerWChar, out charsRead, IntPtr.Zero);
bytesRead = charsRead * BytesPerWChar;
}
}
#endif // !FEATURE_PAL
if (readSuccess)
return Win32Native.ERROR_SUCCESS;
int errorCode = Marshal.GetLastWin32Error();
// For pipes that are closing or broken, just stop.
// (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing;
// ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is mot an error, but EOF.)
if (errorCode == Win32Native.ERROR_NO_DATA || errorCode == Win32Native.ERROR_BROKEN_PIPE)
return Win32Native.ERROR_SUCCESS;
return errorCode;
}
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.Process)]
[ResourceConsumption(ResourceScope.Process)]
private static unsafe int WriteFileNative(SafeFileHandle hFile, byte[] bytes, int offset, int count, bool useFileAPIs) {
Contract.Requires(offset >= 0, "offset >= 0");
Contract.Requires(count >= 0, "count >= 0");
Contract.Requires(bytes != null, "bytes != null");
Contract.Requires(bytes.Length >= offset + count, "bytes.Length >= offset + count");
// You can't use the fixed statement on an array of length 0.
if (bytes.Length == 0)
return Win32Native.ERROR_SUCCESS;
bool writeSuccess;
#if !FEATURE_PAL
if (useFileAPIs) {
#endif // !FEATURE_PAL
fixed (byte* p = bytes) {
int numBytesWritten;
writeSuccess = (0 != Win32Native.WriteFile(hFile, p + offset, count, out numBytesWritten, IntPtr.Zero));
Contract.Assert(!writeSuccess || count == numBytesWritten);
}
#if !FEATURE_PAL
} else {
// Note that WriteConsoleW has a max limit on num of chars to write (64K)
// [http://msdn.microsoft.com/en-us/library/ms687401.aspx]
// However, we do not need to worry about that becasue the StreamWriter in Console has
// a much shorter buffer size anyway.
fixed (byte* p = bytes) {
Int32 charsWritten;
writeSuccess = Win32Native.WriteConsoleW(hFile, p + offset, count / BytesPerWChar, out charsWritten, IntPtr.Zero);
Contract.Assert(!writeSuccess || count / BytesPerWChar == charsWritten);
}
}
#endif // !FEATURE_PAL
if (writeSuccess)
return Win32Native.ERROR_SUCCESS;
int errorCode = Marshal.GetLastWin32Error();
// For pipes that are closing or broken, just stop.
// (E.g. ERROR_NO_DATA ("pipe is being closed") is returned when we write to a console that is closing;
// ERROR_BROKEN_PIPE ("pipe was closed") is returned when stdin was closed, which is mot an error, but EOF.)
if (errorCode == Win32Native.ERROR_NO_DATA || errorCode == Win32Native.ERROR_BROKEN_PIPE)
return Win32Native.ERROR_SUCCESS;
return errorCode;
}
[System.Security.SecurityCritical] // auto-generated
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern void WaitForAvailableConsoleInput(SafeFileHandle file, bool isPipe);
}
}

View File

@@ -0,0 +1,84 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
// <OWNER>[....]</OWNER>
//
#if _DEBUG
// This class writes to wherever OutputDebugString writes to. If you don't have
// a Windows app (ie, something hosted in IE), you can use this to redirect Console
// output for some good old-fashioned console spew in MSDEV's debug output window.
// <STRIP>This really shouldn't ship at all, but is intended as a quick, inefficient hack
// for debugging. -- [....], 9/26/2000</STRIP>
using System;
using System.IO;
using System.Text;
using System.Security;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using Microsoft.Win32;
using System.Globalization;
namespace System.IO {
internal class __DebugOutputTextWriter : TextWriter {
private readonly String _consoleType;
internal __DebugOutputTextWriter(String consoleType): base(CultureInfo.InvariantCulture)
{
_consoleType = consoleType;
}
public override Encoding Encoding {
#if FEATURE_CORECLR
[System.Security.SecuritySafeCritical]
#endif
get {
if (Marshal.SystemDefaultCharSize == 1)
return Encoding.Default;
else
return new UnicodeEncoding(false, false);
}
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void Write(char c)
{
OutputDebugString(c.ToString());
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void Write(String str)
{
OutputDebugString(str);
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void Write(char[] array)
{
if (array != null)
OutputDebugString(new String(array));
}
[System.Security.SecuritySafeCritical] // auto-generated
public override void WriteLine(String str)
{
if (str != null)
OutputDebugString(_consoleType + str);
else
OutputDebugString("<null>");
OutputDebugString(new String(CoreNewLine));
}
[System.Security.SecurityCritical] // auto-generated
[DllImport(Win32Native.KERNEL32, CharSet=CharSet.Auto)]
[SuppressUnmanagedCodeSecurityAttribute()]
[ResourceExposure(ResourceScope.None)]
private static extern void OutputDebugString(String output);
}
}
#endif // _DEBUG

View File

@@ -0,0 +1,237 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: __Error
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: Centralized error methods for the IO package.
** Mostly useful for translating Win32 HRESULTs into meaningful
** error strings & exceptions.
**
**
===========================================================*/
using System;
using System.Runtime.InteropServices;
#if !MONO
using Win32Native = Microsoft.Win32.Win32Native;
#endif
using System.Text;
using System.Globalization;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics.Contracts;
namespace System.IO {
[Pure]
internal static class __Error
{
internal static void EndOfFile() {
throw new EndOfStreamException(Environment.GetResourceString("IO.EOF_ReadBeyondEOF"));
}
internal static void FileNotOpen() {
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_FileClosed"));
}
internal static void StreamIsClosed() {
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_StreamClosed"));
}
internal static void MemoryStreamNotExpandable() {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_MemStreamNotExpandable"));
}
internal static void ReaderClosed() {
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_ReaderClosed"));
}
internal static void ReadNotSupported() {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnreadableStream"));
}
internal static void SeekNotSupported() {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnseekableStream"));
}
internal static void WrongAsyncResult() {
throw new ArgumentException(Environment.GetResourceString("Arg_WrongAsyncResult"));
}
internal static void EndReadCalledTwice() {
// Should ideally be InvalidOperationExc but we can't maitain parity with Stream and FileStream without some work
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndReadCalledMultiple"));
}
internal static void EndWriteCalledTwice() {
// Should ideally be InvalidOperationExc but we can't maintain parity with Stream and FileStream without some work
throw new ArgumentException(Environment.GetResourceString("InvalidOperation_EndWriteCalledMultiple"));
}
// Given a possible fully qualified path, ensure that we have path
// discovery permission to that path. If we do not, return just the
// file name. If we know it is a directory, then don't return the
// directory name.
[System.Security.SecurityCritical] // auto-generated
internal static String GetDisplayablePath(String path, bool isInvalidPath)
{
if (String.IsNullOrEmpty(path))
return String.Empty;
// Is it a fully qualified path?
bool isFullyQualified = false;
if (path.Length < 2)
return path;
if (Path.IsDirectorySeparator(path[0]) && Path.IsDirectorySeparator(path[1]))
isFullyQualified = true;
else if (path[1] == Path.VolumeSeparatorChar) {
isFullyQualified = true;
}
if (!isFullyQualified && !isInvalidPath)
return path;
bool safeToReturn = false;
try {
if (!isInvalidPath) {
#if !FEATURE_CORECLR
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, new String[] { path }, false, false).Demand();
#endif
safeToReturn = true;
}
}
catch (SecurityException) {
}
catch (ArgumentException) {
// ? and * characters cause ArgumentException to be thrown from HasIllegalCharacters
// inside FileIOPermission.AddPathList
}
catch (NotSupportedException) {
// paths like "!Bogus\\dir:with/junk_.in it" can cause NotSupportedException to be thrown
// from Security.Util.StringExpressionSet.CanonicalizePath when ':' is found in the path
// beyond string index position 1.
}
if (!safeToReturn) {
if (Path.IsDirectorySeparator(path[path.Length - 1]))
path = Environment.GetResourceString("IO.IO_NoPermissionToDirectoryName");
else
path = Path.GetFileName(path);
}
return path;
}
#if !MONO
[System.Security.SecuritySafeCritical] // auto-generated
internal static void WinIOError() {
int errorCode = Marshal.GetLastWin32Error();
WinIOError(errorCode, String.Empty);
}
// After calling GetLastWin32Error(), it clears the last error field,
// so you must save the HResult and pass it to this method. This method
// will determine the appropriate exception to throw dependent on your
// error, and depending on the error, insert a string into the message
// gotten from the ResourceManager.
[System.Security.SecurityCritical] // auto-generated
internal static void WinIOError(int errorCode, String maybeFullPath) {
// This doesn't have to be perfect, but is a perf optimization.
bool isInvalidPath = errorCode == Win32Native.ERROR_INVALID_NAME || errorCode == Win32Native.ERROR_BAD_PATHNAME;
String str = GetDisplayablePath(maybeFullPath, isInvalidPath);
switch (errorCode) {
case Win32Native.ERROR_FILE_NOT_FOUND:
if (str.Length == 0)
throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound"));
else
throw new FileNotFoundException(Environment.GetResourceString("IO.FileNotFound_FileName", str), str);
case Win32Native.ERROR_PATH_NOT_FOUND:
if (str.Length == 0)
throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_NoPathName"));
else
throw new DirectoryNotFoundException(Environment.GetResourceString("IO.PathNotFound_Path", str));
case Win32Native.ERROR_ACCESS_DENIED:
if (str.Length == 0)
throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_NoPathName"));
else
throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_IODenied_Path", str));
case Win32Native.ERROR_ALREADY_EXISTS:
if (str.Length == 0)
goto default;
throw new IOException(Environment.GetResourceString("IO.IO_AlreadyExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
case Win32Native.ERROR_FILENAME_EXCED_RANGE:
throw new PathTooLongException(Environment.GetResourceString("IO.PathTooLong"));
case Win32Native.ERROR_INVALID_DRIVE:
throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", str));
case Win32Native.ERROR_INVALID_PARAMETER:
throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
case Win32Native.ERROR_SHARING_VIOLATION:
if (str.Length == 0)
throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_NoFileName"), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
else
throw new IOException(Environment.GetResourceString("IO.IO_SharingViolation_File", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
case Win32Native.ERROR_FILE_EXISTS:
if (str.Length == 0)
goto default;
throw new IOException(Environment.GetResourceString("IO.IO_FileExists_Name", str), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
case Win32Native.ERROR_OPERATION_ABORTED:
throw new OperationCanceledException();
default:
throw new IOException(Win32Native.GetMessage(errorCode), Win32Native.MakeHRFromErrorCode(errorCode), maybeFullPath);
}
}
// An alternative to WinIOError with friendlier messages for drives
[System.Security.SecuritySafeCritical] // auto-generated
internal static void WinIODriveError(String driveName) {
int errorCode = Marshal.GetLastWin32Error();
WinIODriveError(driveName, errorCode);
}
[System.Security.SecurityCritical] // auto-generated
internal static void WinIODriveError(String driveName, int errorCode)
{
switch (errorCode) {
case Win32Native.ERROR_PATH_NOT_FOUND:
case Win32Native.ERROR_INVALID_DRIVE:
throw new DriveNotFoundException(Environment.GetResourceString("IO.DriveNotFound_Drive", driveName));
default:
WinIOError(errorCode, driveName);
break;
}
}
#endif
internal static void WriteNotSupported() {
throw new NotSupportedException(Environment.GetResourceString("NotSupported_UnwritableStream"));
}
internal static void WriterClosed() {
throw new ObjectDisposedException(null, Environment.GetResourceString("ObjectDisposed_WriterClosed"));
}
#if !MONO
// From WinError.h
internal const int ERROR_FILE_NOT_FOUND = Win32Native.ERROR_FILE_NOT_FOUND;
internal const int ERROR_PATH_NOT_FOUND = Win32Native.ERROR_PATH_NOT_FOUND;
internal const int ERROR_ACCESS_DENIED = Win32Native.ERROR_ACCESS_DENIED;
internal const int ERROR_INVALID_PARAMETER = Win32Native.ERROR_INVALID_PARAMETER;
#endif
}
}

View File

@@ -0,0 +1,33 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//=============================================================================
//
// Class: __HResults
//
// <OWNER>[....]</OWNER>
//
// Author: Automatically generated
//
// Purpose: Define HResult constants. Every exception has one of these.
//
// Date: 98/08/31 11:57:11 AM
//
//===========================================================================*/
namespace System.IO {
using System;
// Only static data no need to serialize
internal static class __HResults
{
// These use an error code from WinError.h
public const int COR_E_ENDOFSTREAM = unchecked((int)0x80070026); // OS defined
public const int COR_E_FILELOAD = unchecked((int)0x80131621);
public const int COR_E_FILENOTFOUND = unchecked((int)0x80070002);
public const int COR_E_DIRECTORYNOTFOUND = unchecked((int)0x80070003);
public const int COR_E_PATHTOOLONG = unchecked((int)0x800700CE);
public const int COR_E_IO = unchecked((int)0x80131620);
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,432 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: BinaryWriter
**
** <OWNER>gpaperin</OWNER>
**
** Purpose: Provides a way to write primitives types in
** binary from a Stream, while also supporting writing Strings
** in a particular encoding.
**
**
===========================================================*/
using System;
using System.Runtime;
using System.Runtime.Serialization;
using System.Text;
using System.Diagnostics.Contracts;
namespace System.IO {
// This abstract base class represents a writer that can write
// primitives to an arbitrary stream. A subclass can override methods to
// give unique encodings.
//
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class BinaryWriter : IDisposable
{
public static readonly BinaryWriter Null = new BinaryWriter();
protected Stream OutStream;
private byte[] _buffer; // temp space for writing primitives to.
private Encoding _encoding;
private Encoder _encoder;
[OptionalField] // New in .NET FX 4.5. False is the right default value.
private bool _leaveOpen;
// This field should never have been serialized and has not been used since before v2.0.
// However, this type is serializable, and we need to keep the field name around when deserializing.
// Also, we'll make .NET FX 4.5 not break if it's missing.
#pragma warning disable 169
[OptionalField]
private char[] _tmpOneCharBuffer;
#pragma warning restore 169
// Perf optimization stuff
private byte[] _largeByteBuffer; // temp space for writing chars.
private int _maxChars; // max # of chars we can put in _largeByteBuffer
// Size should be around the max number of chars/string * Encoding's max bytes/char
private const int LargeByteBufferSize = 256;
// Protected default constructor that sets the output stream
// to a null stream (a bit bucket).
protected BinaryWriter()
{
OutStream = Stream.Null;
_buffer = new byte[16];
_encoding = new UTF8Encoding(false, true);
_encoder = _encoding.GetEncoder();
}
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public BinaryWriter(Stream output) : this(output, new UTF8Encoding(false, true), false)
{
}
public BinaryWriter(Stream output, Encoding encoding) : this(output, encoding, false)
{
}
public BinaryWriter(Stream output, Encoding encoding, bool leaveOpen)
{
if (output==null)
throw new ArgumentNullException("output");
if (encoding==null)
throw new ArgumentNullException("encoding");
if (!output.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
Contract.EndContractBlock();
OutStream = output;
_buffer = new byte[16];
_encoding = encoding;
_encoder = _encoding.GetEncoder();
_leaveOpen = leaveOpen;
}
// Closes this writer and releases any system resources associated with the
// writer. Following a call to Close, any operations on the writer
// may raise exceptions.
public virtual void Close()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (disposing) {
if (_leaveOpen)
OutStream.Flush();
else
OutStream.Close();
}
}
public void Dispose()
{
Dispose(true);
}
/*
* Returns the stream associate with the writer. It flushes all pending
* writes before returning. All subclasses should override Flush to
* ensure that all buffered data is sent to the stream.
*/
public virtual Stream BaseStream {
get {
Flush();
return OutStream;
}
}
// Clears all buffers for this writer and causes any buffered data to be
// written to the underlying device.
public virtual void Flush()
{
OutStream.Flush();
}
public virtual long Seek(int offset, SeekOrigin origin)
{
return OutStream.Seek(offset, origin);
}
// Writes a boolean to this stream. A single byte is written to the stream
// with the value 0 representing false or the value 1 representing true.
//
public virtual void Write(bool value) {
_buffer[0] = (byte) (value ? 1 : 0);
OutStream.Write(_buffer, 0, 1);
}
// Writes a byte to this stream. The current position of the stream is
// advanced by one.
//
#if !FEATURE_CORECLR
[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
#endif
public virtual void Write(byte value)
{
OutStream.WriteByte(value);
}
// Writes a signed byte to this stream. The current position of the stream
// is advanced by one.
//
[CLSCompliant(false)]
public virtual void Write(sbyte value)
{
OutStream.WriteByte((byte) value);
}
// Writes a byte array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the byte array.
//
public virtual void Write(byte[] buffer) {
if (buffer == null)
throw new ArgumentNullException("buffer");
Contract.EndContractBlock();
OutStream.Write(buffer, 0, buffer.Length);
}
// Writes a section of a byte array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the byte array.
//
public virtual void Write(byte[] buffer, int index, int count) {
OutStream.Write(buffer, index, count);
}
// Writes a character to this stream. The current position of the stream is
// advanced by two.
// Note this method cannot handle surrogates properly in UTF-8.
//
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual void Write(char ch) {
if (Char.IsSurrogate(ch))
throw new ArgumentException(Environment.GetResourceString("Arg_SurrogatesNotAllowedAsSingleChar"));
Contract.EndContractBlock();
Contract.Assert(_encoding.GetMaxByteCount(1) <= 16, "_encoding.GetMaxByteCount(1) <= 16)");
int numBytes = 0;
fixed(byte * pBytes = _buffer) {
numBytes = _encoder.GetBytes(&ch, 1, pBytes, 16, true);
}
OutStream.Write(_buffer, 0, numBytes);
}
// Writes a character array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the character array.
//
public virtual void Write(char[] chars)
{
if (chars == null)
throw new ArgumentNullException("chars");
Contract.EndContractBlock();
byte[] bytes = _encoding.GetBytes(chars, 0, chars.Length);
OutStream.Write(bytes, 0, bytes.Length);
}
// Writes a section of a character array to this stream.
//
// This default implementation calls the Write(Object, int, int)
// method to write the character array.
//
public virtual void Write(char[] chars, int index, int count)
{
byte[] bytes = _encoding.GetBytes(chars, index, count);
OutStream.Write(bytes, 0, bytes.Length);
}
// Writes a double to this stream. The current position of the stream is
// advanced by eight.
//
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual void Write(double value)
{
#if MONO
OutStream.Write (Mono.Security.BitConverterLE.GetBytes (value), 0, 8);
#else
ulong TmpValue = *(ulong *)&value;
_buffer[0] = (byte) TmpValue;
_buffer[1] = (byte) (TmpValue >> 8);
_buffer[2] = (byte) (TmpValue >> 16);
_buffer[3] = (byte) (TmpValue >> 24);
_buffer[4] = (byte) (TmpValue >> 32);
_buffer[5] = (byte) (TmpValue >> 40);
_buffer[6] = (byte) (TmpValue >> 48);
_buffer[7] = (byte) (TmpValue >> 56);
OutStream.Write(_buffer, 0, 8);
#endif
}
public virtual void Write(decimal value)
{
Decimal.GetBytes(value,_buffer);
OutStream.Write(_buffer, 0, 16);
}
// Writes a two-byte signed integer to this stream. The current position of
// the stream is advanced by two.
//
public virtual void Write(short value)
{
_buffer[0] = (byte) value;
_buffer[1] = (byte) (value >> 8);
OutStream.Write(_buffer, 0, 2);
}
// Writes a two-byte unsigned integer to this stream. The current position
// of the stream is advanced by two.
//
[CLSCompliant(false)]
public virtual void Write(ushort value)
{
_buffer[0] = (byte) value;
_buffer[1] = (byte) (value >> 8);
OutStream.Write(_buffer, 0, 2);
}
// Writes a four-byte signed integer to this stream. The current position
// of the stream is advanced by four.
//
public virtual void Write(int value)
{
_buffer[0] = (byte) value;
_buffer[1] = (byte) (value >> 8);
_buffer[2] = (byte) (value >> 16);
_buffer[3] = (byte) (value >> 24);
OutStream.Write(_buffer, 0, 4);
}
// Writes a four-byte unsigned integer to this stream. The current position
// of the stream is advanced by four.
//
[CLSCompliant(false)]
public virtual void Write(uint value)
{
_buffer[0] = (byte) value;
_buffer[1] = (byte) (value >> 8);
_buffer[2] = (byte) (value >> 16);
_buffer[3] = (byte) (value >> 24);
OutStream.Write(_buffer, 0, 4);
}
// Writes an eight-byte signed integer to this stream. The current position
// of the stream is advanced by eight.
//
public virtual void Write(long value)
{
_buffer[0] = (byte) value;
_buffer[1] = (byte) (value >> 8);
_buffer[2] = (byte) (value >> 16);
_buffer[3] = (byte) (value >> 24);
_buffer[4] = (byte) (value >> 32);
_buffer[5] = (byte) (value >> 40);
_buffer[6] = (byte) (value >> 48);
_buffer[7] = (byte) (value >> 56);
OutStream.Write(_buffer, 0, 8);
}
// Writes an eight-byte unsigned integer to this stream. The current
// position of the stream is advanced by eight.
//
[CLSCompliant(false)]
public virtual void Write(ulong value)
{
_buffer[0] = (byte) value;
_buffer[1] = (byte) (value >> 8);
_buffer[2] = (byte) (value >> 16);
_buffer[3] = (byte) (value >> 24);
_buffer[4] = (byte) (value >> 32);
_buffer[5] = (byte) (value >> 40);
_buffer[6] = (byte) (value >> 48);
_buffer[7] = (byte) (value >> 56);
OutStream.Write(_buffer, 0, 8);
}
// Writes a float to this stream. The current position of the stream is
// advanced by four.
//
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual void Write(float value)
{
#if MONO
OutStream.Write (Mono.Security.BitConverterLE.GetBytes (value), 0, 4);
#else
uint TmpValue = *(uint *)&value;
_buffer[0] = (byte) TmpValue;
_buffer[1] = (byte) (TmpValue >> 8);
_buffer[2] = (byte) (TmpValue >> 16);
_buffer[3] = (byte) (TmpValue >> 24);
OutStream.Write(_buffer, 0, 4);
#endif
}
// Writes a length-prefixed string to this stream in the BinaryWriter's
// current Encoding. This method first writes the length of the string as
// a four-byte unsigned integer, and then writes that many characters
// to the stream.
//
[System.Security.SecuritySafeCritical] // auto-generated
public unsafe virtual void Write(String value)
{
if (value==null)
throw new ArgumentNullException("value");
Contract.EndContractBlock();
int len = _encoding.GetByteCount(value);
Write7BitEncodedInt(len);
if (_largeByteBuffer == null) {
_largeByteBuffer = new byte[LargeByteBufferSize];
_maxChars = LargeByteBufferSize / _encoding.GetMaxByteCount(1);
}
if (len <= LargeByteBufferSize) {
//Contract.Assert(len == _encoding.GetBytes(chars, 0, chars.Length, _largeByteBuffer, 0), "encoding's GetByteCount & GetBytes gave different answers! encoding type: "+_encoding.GetType().Name);
_encoding.GetBytes(value, 0, value.Length, _largeByteBuffer, 0);
OutStream.Write(_largeByteBuffer, 0, len);
}
else {
// Aggressively try to not allocate memory in this loop for
// runtime performance reasons. Use an Encoder to write out
// the string correctly (handling surrogates crossing buffer
// boundaries properly).
int charStart = 0;
int numLeft = value.Length;
#if _DEBUG
int totalBytes = 0;
#endif
while (numLeft > 0) {
// Figure out how many chars to process this round.
int charCount = (numLeft > _maxChars) ? _maxChars : numLeft;
int byteLen;
fixed(char* pChars = value) {
fixed(byte* pBytes = _largeByteBuffer) {
byteLen = _encoder.GetBytes(pChars + charStart, charCount, pBytes, LargeByteBufferSize, charCount == numLeft);
}
}
#if _DEBUG
totalBytes += byteLen;
Contract.Assert (totalBytes <= len && byteLen <= LargeByteBufferSize, "BinaryWriter::Write(String) - More bytes encoded than expected!");
#endif
OutStream.Write(_largeByteBuffer, 0, byteLen);
charStart += charCount;
numLeft -= charCount;
}
#if _DEBUG
Contract.Assert(totalBytes == len, "BinaryWriter::Write(String) - Didn't write out all the bytes!");
#endif
}
}
protected void Write7BitEncodedInt(int value) {
// Write out an int 7 bits at a time. The high bit of the byte,
// when on, tells reader to continue reading more bytes.
uint v = (uint) value; // support negative numbers
while (v >= 0x80) {
Write((byte) (v | 0x80));
v >>= 7;
}
Write((byte)v);
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,48 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: DirectoryNotFoundException
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: Exception for accessing a path that doesn't exist.
**
**
===========================================================*/
using System;
using System.Runtime.Serialization;
namespace System.IO {
/*
* Thrown when trying to access a directory that doesn't exist on disk.
* From COM Interop, this exception is thrown for 2 HRESULTS:
* the Win32 errorcode-as-HRESULT ERROR_PATH_NOT_FOUND (0x80070003)
* and STG_E_PATHNOTFOUND (0x80030003).
*/
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class DirectoryNotFoundException : IOException {
public DirectoryNotFoundException()
: base(Environment.GetResourceString("Arg_DirectoryNotFoundException")) {
SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
}
public DirectoryNotFoundException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
}
public DirectoryNotFoundException(String message, Exception innerException)
: base(message, innerException) {
SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
}
protected DirectoryNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}

View File

@@ -0,0 +1,298 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: DriveInfo
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: Exposes routines for exploring a drive.
**
**
===========================================================*/
using System;
using System.Text;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
namespace System.IO
{
// Matches Win32's DRIVE_XXX #defines from winbase.h
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum DriveType
{
Unknown = 0,
NoRootDirectory = 1,
Removable = 2,
Fixed = 3,
Network = 4,
CDRom = 5,
Ram = 6
}
// Ideally we'll get a better security permission, but possibly
// not for Whidbey.
[Serializable]
[ComVisible(true)]
public sealed class DriveInfo : ISerializable
{
private String _name;
private const String NameField = "_name"; // For serialization
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public DriveInfo(String driveName)
{
if (driveName == null)
throw new ArgumentNullException("driveName");
Contract.EndContractBlock();
if (driveName.Length == 1)
_name = driveName + ":\\";
else {
// GetPathRoot does not check all invalid characters
Path.CheckInvalidPathChars(driveName);
_name = Path.GetPathRoot(driveName);
// Disallow null or empty drive letters and UNC paths
if (_name == null || _name.Length == 0 || _name.StartsWith("\\\\", StringComparison.Ordinal))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDriveLetterOrRootDir"));
}
// We want to normalize to have a trailing backslash so we don't have two equivalent forms and
// because some Win32 API don't work without it.
if (_name.Length == 2 && _name[1] == ':') {
_name = _name + "\\";
}
// Now verify that the drive letter could be a real drive name.
// On Windows this means it's between A and Z, ignoring case.
// On a Unix platform, perhaps this should be a device name with
// a partition like /dev/hdc0, or possibly a mount point.
char letter = driveName[0];
if (!((letter >= 'A' && letter <= 'Z') || (letter >= 'a' && letter <= 'z')))
throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDriveLetterOrRootDir"));
// Now do a security check.
String demandPath = _name + '.';
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPath).Demand();
}
[System.Security.SecurityCritical] // auto-generated
private DriveInfo(SerializationInfo info, StreamingContext context)
{
// Need to add in a security check here once it has been spec'ed.
_name = (String) info.GetValue(NameField, typeof(String));
// Now do a security check.
String demandPath = _name + '.';
new FileIOPermission(FileIOPermissionAccess.PathDiscovery, demandPath).Demand();
}
public String Name {
get { return _name; }
}
public DriveType DriveType {
[System.Security.SecuritySafeCritical] // auto-generated
get {
// GetDriveType can't fail
return (DriveType) Win32Native.GetDriveType(Name);
}
}
public String DriveFormat {
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
get {
const int volNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
const int fileSystemNameLen = 50;
StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
int serialNumber, maxFileNameLen, fileSystemFlags;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
bool r = Win32Native.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
if (!r) {
int errorCode = Marshal.GetLastWin32Error();
__Error.WinIODriveError(Name, errorCode);
}
}
finally {
Win32Native.SetErrorMode(oldMode);
}
return fileSystemName.ToString();
}
}
public bool IsReady {
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
get {
return Directory.InternalExists(Name);
}
}
public long AvailableFreeSpace {
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
get {
long userBytes, totalBytes, freeBytes;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
bool r = Win32Native.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
__Error.WinIODriveError(Name);
}
finally {
Win32Native.SetErrorMode(oldMode);
}
return userBytes;
}
}
public long TotalFreeSpace {
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
get {
long userBytes, totalBytes, freeBytes;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
bool r = Win32Native.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
__Error.WinIODriveError(Name);
}
finally {
Win32Native.SetErrorMode(oldMode);
}
return freeBytes;
}
}
public long TotalSize {
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
get {
// Don't cache this, to handle variable sized floppy drives
// or other various removable media drives.
long userBytes, totalBytes, freeBytes;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
bool r = Win32Native.GetDiskFreeSpaceEx(Name, out userBytes, out totalBytes, out freeBytes);
if (!r)
__Error.WinIODriveError(Name);
}
finally {
Win32Native.SetErrorMode(oldMode);
}
return totalBytes;
}
}
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public static DriveInfo[] GetDrives()
{
// Directory.GetLogicalDrives demands unmanaged code permission
String[] drives = Directory.GetLogicalDrives();
DriveInfo[] di = new DriveInfo[drives.Length];
for(int i=0; i<drives.Length; i++)
di[i] = new DriveInfo(drives[i]);
return di;
}
public DirectoryInfo RootDirectory {
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
get {
return new DirectoryInfo(Name);
}
}
// Null is a valid volume label.
public String VolumeLabel {
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
get {
// NTFS uses a limit of 32 characters for the volume label,
// as of Windows Server 2003.
const int volNameLen = 50;
StringBuilder volumeName = new StringBuilder(volNameLen);
const int fileSystemNameLen = 50;
StringBuilder fileSystemName = new StringBuilder(fileSystemNameLen);
int serialNumber, maxFileNameLen, fileSystemFlags;
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
bool r = Win32Native.GetVolumeInformation(Name, volumeName, volNameLen, out serialNumber, out maxFileNameLen, out fileSystemFlags, fileSystemName, fileSystemNameLen);
if (!r) {
int errorCode = Marshal.GetLastWin32Error();
// Win9x appears to return ERROR_INVALID_DATA when a
// drive doesn't exist.
if (errorCode == Win32Native.ERROR_INVALID_DATA)
errorCode = Win32Native.ERROR_INVALID_DRIVE;
__Error.WinIODriveError(Name, errorCode);
}
}
finally {
Win32Native.SetErrorMode(oldMode);
}
return volumeName.ToString();
}
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Process, ResourceScope.Process)]
set {
String demandPath = _name + '.';
new FileIOPermission(FileIOPermissionAccess.Write, demandPath).Demand();
int oldMode = Win32Native.SetErrorMode(Win32Native.SEM_FAILCRITICALERRORS);
try {
bool r = Win32Native.SetVolumeLabel(Name, value);
if (!r) {
int errorCode = Marshal.GetLastWin32Error();
// Provide better message
if (errorCode == Win32Native.ERROR_ACCESS_DENIED)
throw new UnauthorizedAccessException(Environment.GetResourceString("InvalidOperation_SetVolumeLabelFailed"));
__Error.WinIODriveError(Name, errorCode);
}
}
finally {
Win32Native.SetErrorMode(oldMode);
}
}
}
public override String ToString()
{
return Name;
}
#if FEATURE_SERIALIZATION
/// <internalonly/>
[System.Security.SecurityCritical]
void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
{
// No need for an additional security check - everything is public.
info.AddValue(NameField, _name, typeof(String));
}
#endif
}
}

View File

@@ -0,0 +1,43 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
//============================================================
//
// Class: DriveNotFoundException
//
// <OWNER>[....]</OWNER>
//
// Purpose: Exception for accessing a drive that is not available.
//
//
//============================================================
using System;
using System.Runtime.Serialization;
namespace System.IO {
//Thrown when trying to access a drive that is not availabe.
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class DriveNotFoundException : IOException {
public DriveNotFoundException()
: base(Environment.GetResourceString("Arg_DriveNotFoundException")) {
SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
}
public DriveNotFoundException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
}
public DriveNotFoundException(String message, Exception innerException)
: base(message, innerException) {
SetErrorCode(__HResults.COR_E_DIRECTORYNOTFOUND);
}
protected DriveNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context) {
}
}
}

View File

@@ -0,0 +1,45 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: EndOfStreamException
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: Exception to be thrown when reading past end-of-file.
**
**
===========================================================*/
using System;
using System.Runtime.Serialization;
namespace System.IO {
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class EndOfStreamException : IOException
{
public EndOfStreamException()
: base(Environment.GetResourceString("Arg_EndOfStreamException")) {
SetErrorCode(__HResults.COR_E_ENDOFSTREAM);
}
public EndOfStreamException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_ENDOFSTREAM);
}
public EndOfStreamException(String message, Exception innerException)
: base(message, innerException) {
SetErrorCode(__HResults.COR_E_ENDOFSTREAM);
}
protected EndOfStreamException(SerializationInfo info, StreamingContext context) : base (info, context) {
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,43 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Enum: FileAccess
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: Enum describing whether you want read and/or write
** permission to a file.
**
**
===========================================================*/
using System;
namespace System.IO {
// Contains constants for specifying the access you want for a file.
// You can have Read, Write or ReadWrite access.
//
[Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum FileAccess
{
// Specifies read access to the file. Data can be read from the file and
// the file pointer can be moved. Combine with WRITE for read-write access.
Read = 1,
// Specifies write access to the file. Data can be written to the file and
// the file pointer can be moved. Combine with READ for read-write access.
Write = 2,
// Specifies read and write access to the file. Data can be written to the
// file and the file pointer can be moved. Data can also be read from the
// file.
ReadWrite = 3,
}
}

View File

@@ -0,0 +1,53 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: FileAttributes
**
** Purpose: File attribute flags corresponding to NT's flags.
**
**
===========================================================*/
using System;
namespace System.IO {
// File attributes for use with the FileEnumerator class.
// These constants correspond to the constants in WinNT.h.
//
[Serializable]
[Flags]
[System.Runtime.InteropServices.ComVisible(true)]
public enum FileAttributes
{
// From WinNT.h (FILE_ATTRIBUTE_XXX)
ReadOnly = 0x1,
Hidden = 0x2,
System = 0x4,
Directory = 0x10,
Archive = 0x20,
Device = 0x40,
Normal = 0x80,
Temporary = 0x100,
SparseFile = 0x200,
ReparsePoint = 0x400,
Compressed = 0x800,
Offline = 0x1000,
NotContentIndexed = 0x2000,
Encrypted = 0x4000,
#if !FEATURE_NETCORE
#if FEATURE_COMINTEROP
[System.Runtime.InteropServices.ComVisible(false)]
#endif // FEATURE_COMINTEROP
IntegrityStream = 0x8000,
#if FEATURE_COMINTEROP
[System.Runtime.InteropServices.ComVisible(false)]
#endif // FEATURE_COMINTEROP
NoScrubData = 0x20000,
#endif
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,209 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Class: FileLoadException
**
** <OWNER>[....]</OWNER>
** <OWNER>[....]</OWNER>
**
**
** Purpose: Exception for failure to load a file that was successfully found.
**
**
===========================================================*/
using System;
using System.Globalization;
using System.Runtime.Serialization;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Security;
using System.Security.Permissions;
using System.Runtime.Versioning;
using SecurityException = System.Security.SecurityException;
namespace System.IO {
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class FileLoadException : IOException {
private String _fileName; // the name of the file we could not load.
private String _fusionLog; // fusion log (when applicable)
public FileLoadException()
: base(Environment.GetResourceString("IO.FileLoad")) {
SetErrorCode(__HResults.COR_E_FILELOAD);
}
public FileLoadException(String message)
: base(message) {
SetErrorCode(__HResults.COR_E_FILELOAD);
}
public FileLoadException(String message, Exception inner)
: base(message, inner) {
SetErrorCode(__HResults.COR_E_FILELOAD);
}
public FileLoadException(String message, String fileName) : base(message)
{
SetErrorCode(__HResults.COR_E_FILELOAD);
_fileName = fileName;
}
public FileLoadException(String message, String fileName, Exception inner)
: base(message, inner) {
SetErrorCode(__HResults.COR_E_FILELOAD);
_fileName = fileName;
}
public override String Message
{
get {
SetMessageField();
return _message;
}
}
private void SetMessageField()
{
if (_message == null)
_message = FormatFileLoadExceptionMessage(_fileName, HResult);
}
public String FileName {
get { return _fileName; }
}
#if FEATURE_LEGACYNETCF
// override Data property to populate FileLoadException with Hresult
public override System.Collections.IDictionary Data {
[System.Security.SecuritySafeCritical]
get {
var _data = base.Data;
if (CompatibilitySwitches.IsAppEarlierThanWindowsPhone8 && !_data.Contains("HResult"))
{
_data.Add("HResult", HResult);
}
return _data;
}
}
#endif //FEATURE_LEGACYNETCF
public override String ToString()
{
String s = GetType().FullName + ": " + Message;
if (_fileName != null && _fileName.Length != 0)
s += Environment.NewLine + Environment.GetResourceString("IO.FileName_Name", _fileName);
if (InnerException != null)
s = s + " ---> " + InnerException.ToString();
if (StackTrace != null)
s += Environment.NewLine + StackTrace;
#if FEATURE_FUSION
try
{
if(FusionLog!=null)
{
if (s==null)
s=" ";
s+=Environment.NewLine;
s+=Environment.NewLine;
s+=FusionLog;
}
}
catch(SecurityException)
{
}
#endif // FEATURE_FUSION
return s;
}
protected FileLoadException(SerializationInfo info, StreamingContext context) : base (info, context) {
// Base class constructor will check info != null.
_fileName = info.GetString("FileLoad_FileName");
try
{
_fusionLog = info.GetString("FileLoad_FusionLog");
}
catch
{
_fusionLog = null;
}
}
private FileLoadException(String fileName, String fusionLog,int hResult)
: base(null)
{
SetErrorCode(hResult);
_fileName = fileName;
_fusionLog=fusionLog;
SetMessageField();
}
#if FEATURE_FUSION
public String FusionLog {
[System.Security.SecuritySafeCritical] // auto-generated
[SecurityPermissionAttribute( SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlEvidence | SecurityPermissionFlag.ControlPolicy)]
get { return _fusionLog; }
}
#endif // FEATURE_FUSION
#if FEATURE_SERIALIZATION
[System.Security.SecurityCritical] // auto-generated_required
public override void GetObjectData(SerializationInfo info, StreamingContext context) {
// Serialize data for our base classes. base will verify info != null.
base.GetObjectData(info, context);
// Serialize data for this class
info.AddValue("FileLoad_FileName", _fileName, typeof(String));
try
{
info.AddValue("FileLoad_FusionLog", FusionLog, typeof(String));
}
catch (SecurityException)
{
}
}
#endif
[System.Security.SecuritySafeCritical] // auto-generated
internal static String FormatFileLoadExceptionMessage(String fileName,
int hResult)
{
string format = null;
GetFileLoadExceptionMessage(hResult, JitHelpers.GetStringHandleOnStack(ref format));
string message = null;
GetMessageForHR(hResult, JitHelpers.GetStringHandleOnStack(ref message));
return String.Format(CultureInfo.CurrentCulture, format, fileName, message);
}
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetFileLoadExceptionMessage(int hResult, StringHandleOnStack retString);
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)]
[SuppressUnmanagedCodeSecurity]
private static extern void GetMessageForHR(int hresult, StringHandleOnStack retString);
}
}

View File

@@ -0,0 +1,55 @@
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
/*============================================================
**
** Enum: FileMode
**
** <OWNER>[....]</OWNER>
**
**
** Purpose: Enum describing whether to create a new file or
** open an existing one.
**
**
===========================================================*/
using System;
namespace System.IO {
// Contains constants for specifying how the OS should open a file.
// These will control whether you overwrite a file, open an existing
// file, or some combination thereof.
//
// To append to a file, use Append (which maps to OpenOrCreate then we seek
// to the end of the file). To truncate a file or create it if it doesn't
// exist, use Create.
//
[Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public enum FileMode
{
// Creates a new file. An exception is raised if the file already exists.
CreateNew = 1,
// Creates a new file. If the file already exists, it is overwritten.
Create = 2,
// Opens an existing file. An exception is raised if the file does not exist.
Open = 3,
// Opens the file if it exists. Otherwise, creates a new file.
OpenOrCreate = 4,
// Opens an existing file. Once opened, the file is truncated so that its
// size is zero bytes. The calling process must open the file with at least
// WRITE access. An exception is raised if the file does not exist.
Truncate = 5,
// Opens the file if it exists and seeks to the end. Otherwise,
// creates a new file.
Append = 6,
}
}

Some files were not shown because too many files have changed in this diff Show More