diff --git a/snippets/csharp/Microsoft.Extensions.DependencyModel/DependencyContext/Overview/DependencyContextSnippets.csproj b/snippets/csharp/Microsoft.Extensions.DependencyModel/DependencyContext/Overview/DependencyContextSnippets.csproj index ca81028d32f..3c8d979e9bd 100644 --- a/snippets/csharp/Microsoft.Extensions.DependencyModel/DependencyContext/Overview/DependencyContextSnippets.csproj +++ b/snippets/csharp/Microsoft.Extensions.DependencyModel/DependencyContext/Overview/DependencyContextSnippets.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/Microsoft.SqlServer.Server/SqlFunctionAttribute/Function.csproj b/snippets/csharp/Microsoft.SqlServer.Server/SqlFunctionAttribute/Function.csproj index 58cd6fd697b..e9c8a32a6ff 100644 --- a/snippets/csharp/Microsoft.SqlServer.Server/SqlFunctionAttribute/Function.csproj +++ b/snippets/csharp/Microsoft.SqlServer.Server/SqlFunctionAttribute/Function.csproj @@ -3,6 +3,7 @@ Library net6.0 + enable diff --git a/snippets/csharp/Microsoft.SqlServer.Server/SqlUserDefinedAggregateAttribute/Aggregate.csproj b/snippets/csharp/Microsoft.SqlServer.Server/SqlUserDefinedAggregateAttribute/Aggregate.csproj index 58cd6fd697b..e9c8a32a6ff 100644 --- a/snippets/csharp/Microsoft.SqlServer.Server/SqlUserDefinedAggregateAttribute/Aggregate.csproj +++ b/snippets/csharp/Microsoft.SqlServer.Server/SqlUserDefinedAggregateAttribute/Aggregate.csproj @@ -3,6 +3,7 @@ Library net6.0 + enable diff --git a/snippets/csharp/Microsoft.SqlServer.Server/SqlUserDefinedTypeAttribute/Type.csproj b/snippets/csharp/Microsoft.SqlServer.Server/SqlUserDefinedTypeAttribute/Type.csproj index 58cd6fd697b..e9c8a32a6ff 100644 --- a/snippets/csharp/Microsoft.SqlServer.Server/SqlUserDefinedTypeAttribute/Type.csproj +++ b/snippets/csharp/Microsoft.SqlServer.Server/SqlUserDefinedTypeAttribute/Type.csproj @@ -3,6 +3,7 @@ Library net6.0 + enable diff --git a/snippets/csharp/Microsoft.SqlServer.Server/SqlUserDefinedTypeAttribute/Type1.cs b/snippets/csharp/Microsoft.SqlServer.Server/SqlUserDefinedTypeAttribute/Type1.cs index 23a109770da..52279ee862e 100644 --- a/snippets/csharp/Microsoft.SqlServer.Server/SqlUserDefinedTypeAttribute/Type1.cs +++ b/snippets/csharp/Microsoft.SqlServer.Server/SqlUserDefinedTypeAttribute/Type1.cs @@ -36,13 +36,7 @@ public Int32 Y } } - public bool IsNull - { - get - { - return is_Null; - } - } + public bool IsNull => is_Null; public static Point Null { @@ -74,12 +68,15 @@ public static Point Parse(SqlString s) } // Parse input string here to separate out coordinates - string str = Convert.ToString(s); - string[] xy = str.Split(':'); + string? str = Convert.ToString(s); + string[]? xy = str?.Split(':'); Point pt = new Point(); - pt.X = Convert.ToInt32(xy[0]); - pt.Y = Convert.ToInt32(xy[1]); + if (xy is not null) + { + pt.X = Convert.ToInt32(xy[0]); + pt.Y = Convert.ToInt32(xy[1]); + } return (pt); } @@ -125,9 +122,9 @@ public SqlString Quadrant() //----------------------------------------------------------------------------- // -[SqlUserDefinedType(Format.Native, MaxByteSize=8000)] +[SqlUserDefinedType(Format.Native, MaxByteSize = 8000)] public class SampleType { - //... + //... } // diff --git a/snippets/csharp/System.Collections.Immutable/ImmutableArray`1/Overview/ImmutableArraySnippets.csproj b/snippets/csharp/System.Collections.Immutable/ImmutableArray`1/Overview/ImmutableArraySnippets.csproj index 120e38c3150..8c8d40ddc3a 100644 --- a/snippets/csharp/System.Collections.Immutable/ImmutableArray`1/Overview/ImmutableArraySnippets.csproj +++ b/snippets/csharp/System.Collections.Immutable/ImmutableArray`1/Overview/ImmutableArraySnippets.csproj @@ -3,6 +3,7 @@ Exe net7.0 + enable diff --git a/snippets/csharp/System.DateTime/DateWithTimeZone.cs b/snippets/csharp/System.DateTime/DateWithTimeZone.cs deleted file mode 100644 index e8aa5e05116..00000000000 --- a/snippets/csharp/System.DateTime/DateWithTimeZone.cs +++ /dev/null @@ -1,31 +0,0 @@ -// -using System; - -namespace DateTimeExtensions -{ - [Serializable] - public struct DateWithTimeZone - { - private TimeZoneInfo tz; - private DateTime dt; - - public DateWithTimeZone(DateTime dateValue, TimeZoneInfo timeZone) - { - dt = dateValue; - tz = timeZone ?? TimeZoneInfo.Local; - } - - public TimeZoneInfo TimeZone - { - get { return (tz); } - set { tz = value; } - } - - public DateTime DateTime - { - get { return (dt); } - set { dt = value; } - } - } -} -// diff --git a/snippets/csharp/System.DateTime/Persistence.cs b/snippets/csharp/System.DateTime/Persistence.cs index d0d461d40a5..16585f5f326 100644 --- a/snippets/csharp/System.DateTime/Persistence.cs +++ b/snippets/csharp/System.DateTime/Persistence.cs @@ -1,10 +1,7 @@ -using DateTimeExtensions; -using System; +using System; using System.Collections.Generic; using System.Globalization; using System.IO; -using System.Runtime.Serialization; -using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using System.Xml.Serialization; @@ -29,13 +26,6 @@ public static void Snippets() File.Delete(filenameXml); PersistAsXML(); File.Delete(filenameXml); - - File.Delete(filenameBin); - PersistBinary(); - File.Delete(filenameBin); - - SaveDateWithTimeZone(); - RestoreDateWithTimeZone(); } // @@ -52,7 +42,7 @@ private static void SaveLocalDatesAsString() new DateTime(2015, 1, 10, 1, 16, 0), new DateTime(2014, 12, 20, 21, 45, 0), new DateTime(2014, 6, 2, 15, 14, 0) }; - string output = null; + string? output = null; Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"); Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"); @@ -87,7 +77,7 @@ private static void RestoreLocalDatesFromString() } else { - Console.WriteLine("Cannot parse '{inputValue}'"); + Console.WriteLine($"Cannot parse '{inputValue}'"); } } Console.WriteLine("Restored dates..."); @@ -127,7 +117,7 @@ private static void SaveDatesAsInvariantStrings() new DateTime(2015, 1, 10, 1, 16, 0), new DateTime(2014, 12, 20, 21, 45, 0), new DateTime(2014, 6, 2, 15, 14, 0) }; - string output = null; + string? output = null; Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"); Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"); @@ -318,7 +308,7 @@ public static void PersistAsXML() } catch (InvalidOperationException e) { - Console.WriteLine(e.InnerException.Message); + Console.WriteLine(e.InnerException?.Message); } finally { @@ -326,21 +316,24 @@ public static void PersistAsXML() } // Deserialize the data. - DateTime[] deserializedDates; + DateTime[]? deserializedDates; using (var fs = new FileStream(filenameXml, FileMode.Open)) { - deserializedDates = (DateTime[])serializer.Deserialize(fs); + deserializedDates = (DateTime[]?)serializer.Deserialize(fs); } // Display the dates. Console.WriteLine($"Leap year days from 2000-2100 on an {Thread.CurrentThread.CurrentCulture.Name} system:"); int nItems = 0; - foreach (var dat in deserializedDates) + if (deserializedDates is not null) { - Console.Write($" {dat:d} "); - nItems++; - if (nItems % 5 == 0) - Console.WriteLine(); + foreach (var dat in deserializedDates) + { + Console.Write($" {dat:d} "); + nItems++; + if (nItems % 5 == 0) + Console.WriteLine(); + } } } // The example displays the following output: @@ -351,156 +344,5 @@ public static void PersistAsXML() // 29/02/2060 29/02/2064 29/02/2068 29/02/2072 29/02/2076 // 29/02/2080 29/02/2084 29/02/2088 29/02/2092 29/02/2096 // - - private const string filenameBin = @".\Dates.bin"; - - // - public static void PersistBinary() - { - SaveDatesBinary(); - RestoreDatesBinary(); - } - - private static void SaveDatesBinary() - { - DateTime[] dates = { new DateTime(2014, 6, 14, 6, 32, 0), - new DateTime(2014, 7, 10, 23, 49, 0), - new DateTime(2015, 1, 10, 1, 16, 0), - new DateTime(2014, 12, 20, 21, 45, 0), - new DateTime(2014, 6, 2, 15, 14, 0) }; - var fs = new FileStream(filenameBin, FileMode.Create); - var bin = new BinaryFormatter(); - - Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"); - Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"); - for (int ctr = 0; ctr < dates.Length; ctr++) - { - Console.WriteLine(dates[ctr].ToString("f")); - dates[ctr] = dates[ctr].ToUniversalTime(); - } - bin.Serialize(fs, dates); - fs.Close(); - Console.WriteLine("Saved dates..."); - } - - private static void RestoreDatesBinary() - { - TimeZoneInfo.ClearCachedData(); - Console.WriteLine($"Current Time Zone: {TimeZoneInfo.Local.DisplayName}"); - Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB"); - - FileStream fs = new FileStream(filenameBin, FileMode.Open); - BinaryFormatter bin = new BinaryFormatter(); - var dates = (DateTime[])bin.Deserialize(fs); - fs.Close(); - - Console.WriteLine($"The dates on an {Thread.CurrentThread.CurrentCulture.Name} system:"); - foreach (var value in dates) - Console.WriteLine(value.ToLocalTime().ToString("f")); - - Console.WriteLine("Restored dates..."); - } - // When saved on an en-US system, the example displays the following output: - // Current Time Zone: (UTC-08:00) Pacific Time (US & Canada) - // The dates on an en-US system: - // Saturday, June 14, 2014 6:32 AM - // Thursday, July 10, 2014 11:49 PM - // Saturday, January 10, 2015 1:16 AM - // Saturday, December 20, 2014 9:45 PM - // Monday, June 02, 2014 3:14 PM - // Saved dates... - // - // When restored on an en-GB system, the example displays the following output: - // Current Time Zone: (UTC-6:00) Central Time (US & Canada) - // The dates on an en-GB system: - // 14 June 2014 08:32 - // 11 July 2014 01:49 - // 10 January 2015 03:16 - // 20 December 2014 23:45 - // 02 June 2014 17:14 - // Restored dates... - // - - // - public static void SaveDateWithTimeZone() - { - DateWithTimeZone[] dates = { new DateWithTimeZone(new DateTime(2014, 8, 9, 19, 30, 0), - TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")), - new DateWithTimeZone(new DateTime(2014, 8, 15, 19, 0, 0), - TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time")), - new DateWithTimeZone(new DateTime(2014, 8, 22, 19, 30, 0), - TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")), - new DateWithTimeZone(new DateTime(2014, 8, 28, 19, 0, 0), - TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time")) }; - var fs = new FileStream(@".\Schedule.bin", FileMode.Create); - var formatter = new BinaryFormatter(); - try - { - formatter.Serialize(fs, dates); - // Display dates. - foreach (var date in dates) - { - TimeZoneInfo tz = date.TimeZone; - Console.WriteLine($"{date.DateTime} {(tz.IsDaylightSavingTime(date.DateTime) ? tz.DaylightName : tz.StandardName)}"); - } - } - catch (SerializationException e) - { - Console.WriteLine($"Serialization failed. Reason: {e.Message}"); - } - finally - { - if (fs != null) fs.Close(); - } - } - // The example displays the following output: - // 8/9/2014 7:30:00 PM Eastern Daylight Time - // 8/15/2014 7:00:00 PM Pacific Daylight Time - // 8/22/2014 7:30:00 PM Eastern Daylight Time - // 8/28/2014 7:00:00 PM Eastern Daylight Time - // - - // - public static void RestoreDateWithTimeZone() - { - const string filename = @".\Schedule.bin"; - FileStream fs; - if (File.Exists(filename)) - { - fs = new FileStream(filename, FileMode.Open); - } - else - { - Console.WriteLine("Unable to find file to deserialize."); - return; - } - - var formatter = new BinaryFormatter(); - DateWithTimeZone[] dates; - try - { - dates = (DateWithTimeZone[])formatter.Deserialize(fs); - // Display dates. - foreach (var date in dates) - { - TimeZoneInfo tz = date.TimeZone; - Console.WriteLine($"{ date.DateTime} {(tz.IsDaylightSavingTime(date.DateTime) ? tz.DaylightName : tz.StandardName)}"); - } - } - catch (SerializationException e) - { - Console.WriteLine($"Deserialization failed. Reason: {e.Message}"); - } - finally - { - if (fs != null) fs.Close(); - } - } - // The example displays the following output: - // 8/9/2014 7:30:00 PM Eastern Daylight Time - // 8/15/2014 7:00:00 PM Pacific Daylight Time - // 8/22/2014 7:30:00 PM Eastern Daylight Time - // 8/28/2014 7:00:00 PM Eastern Daylight Time - // } } diff --git a/snippets/csharp/System.DateTime/SystemDateTimeReference.csproj b/snippets/csharp/System.DateTime/SystemDateTimeReference.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.DateTime/SystemDateTimeReference.csproj +++ b/snippets/csharp/System.DateTime/SystemDateTimeReference.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Diagnostics.Tracing/EventSource/Overview/etwtracesmall.csproj b/snippets/csharp/System.Diagnostics.Tracing/EventSource/Overview/etwtracesmall.csproj index 1b96f7bdfe9..d9eecd559e2 100644 --- a/snippets/csharp/System.Diagnostics.Tracing/EventSource/Overview/etwtracesmall.csproj +++ b/snippets/csharp/System.Diagnostics.Tracing/EventSource/Overview/etwtracesmall.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable true Demo.Program diff --git a/snippets/csharp/System.Globalization/CultureInfo/CurrentCulture/changeculture1.cs b/snippets/csharp/System.Globalization/CultureInfo/CurrentCulture/changeculture1.cs deleted file mode 100644 index 301a7504ef8..00000000000 --- a/snippets/csharp/System.Globalization/CultureInfo/CurrentCulture/changeculture1.cs +++ /dev/null @@ -1,36 +0,0 @@ -// -using System; -using System.Globalization; -using System.Threading; - -public class Info : MarshalByRefObject -{ - public void ShowCurrentCulture() - { - Console.WriteLine("Culture of {0} in application domain {1}: {2}", - Thread.CurrentThread.Name, - AppDomain.CurrentDomain.FriendlyName, - CultureInfo.CurrentCulture.Name); - } -} - -public class Example1 -{ - public static void Main() - { - Info inf = new Info(); - // Set the current culture to Dutch (Netherlands). - Thread.CurrentThread.Name = "MainThread"; - Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("nl-NL"); - inf.ShowCurrentCulture(); - - // Create a new application domain. - AppDomain ad = AppDomain.CreateDomain("Domain2"); - Info inf2 = (Info) ad.CreateInstanceAndUnwrap(typeof(Info).Assembly.FullName, "Info"); - inf2.ShowCurrentCulture(); - } -} -// The example displays the following output: -// Culture of MainThread in application domain ChangeCulture1.exe: nl-NL -// Culture of MainThread in application domain Domain2: nl-NL -// diff --git a/snippets/csharp/System.Globalization/CultureInfo/CurrentCulture/changeculture11.cs b/snippets/csharp/System.Globalization/CultureInfo/CurrentCulture/changeculture11.cs index 810afa9ab4c..a3fe1c883cd 100644 --- a/snippets/csharp/System.Globalization/CultureInfo/CurrentCulture/changeculture11.cs +++ b/snippets/csharp/System.Globalization/CultureInfo/CurrentCulture/changeculture11.cs @@ -5,30 +5,30 @@ public class Info11 : MarshalByRefObject { - public void ShowCurrentCulture() - { - Console.WriteLine("Culture of {0} in application domain {1}: {2}", - Thread.CurrentThread.Name, - AppDomain.CurrentDomain.FriendlyName, - CultureInfo.CurrentCulture.Name); - } + public void ShowCurrentCulture() + { + Console.WriteLine("Culture of {0} in application domain {1}: {2}", + Thread.CurrentThread.Name, + AppDomain.CurrentDomain.FriendlyName, + CultureInfo.CurrentCulture.Name); + } } public class Example11 { - public static void Main() - { - Info11 inf = new Info11(); - // Set the current culture to Dutch (Netherlands). - Thread.CurrentThread.Name = "MainThread"; - CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("nl-NL"); - inf.ShowCurrentCulture(); + public static void Main() + { + Info11 inf = new Info11(); + // Set the current culture to Dutch (Netherlands). + Thread.CurrentThread.Name = "MainThread"; + CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("nl-NL"); + inf.ShowCurrentCulture(); - // Create a new application domain. - AppDomain ad = AppDomain.CreateDomain("Domain2"); - Info11 inf2 = (Info11) ad.CreateInstanceAndUnwrap(typeof(Info11).Assembly.FullName, "Info11"); - inf2.ShowCurrentCulture(); - } + // Create a new application domain. + AppDomain ad = AppDomain.CreateDomain("Domain2"); + Info11 inf2 = (Info11)ad.CreateInstanceAndUnwrap(typeof(Info11).Assembly.FullName, "Info11"); + inf2.ShowCurrentCulture(); + } } // The example displays the following output: // Culture of MainThread in application domain ChangeCulture1.exe: nl-NL diff --git a/snippets/csharp/System.Globalization/CultureInfo/CurrentCulture/currentculture.csproj b/snippets/csharp/System.Globalization/CultureInfo/CurrentCulture/currentculture.csproj index e2c8b047250..422acfc0ed0 100644 --- a/snippets/csharp/System.Globalization/CultureInfo/CurrentCulture/currentculture.csproj +++ b/snippets/csharp/System.Globalization/CultureInfo/CurrentCulture/currentculture.csproj @@ -2,7 +2,7 @@ Exe - net6.0 + net4.8 Example5 diff --git a/snippets/csharp/System.Globalization/JapaneseCalendar.ToDateTime/todatetime.csproj b/snippets/csharp/System.Globalization/JapaneseCalendar.ToDateTime/todatetime.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.Globalization/JapaneseCalendar.ToDateTime/todatetime.csproj +++ b/snippets/csharp/System.Globalization/JapaneseCalendar.ToDateTime/todatetime.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.IO/BinaryReader/Overview/BinaryReaderWriter.csproj b/snippets/csharp/System.IO/BinaryReader/Overview/BinaryReaderWriter.csproj index 666d430522a..977e3f1be72 100644 --- a/snippets/csharp/System.IO/BinaryReader/Overview/BinaryReaderWriter.csproj +++ b/snippets/csharp/System.IO/BinaryReader/Overview/BinaryReaderWriter.csproj @@ -2,5 +2,6 @@ library net6.0 + enable diff --git a/snippets/csharp/System.IO/Path/Combine/misc.csproj b/snippets/csharp/System.IO/Path/Combine/misc.csproj index 5080ad5bdb8..21981895620 100644 --- a/snippets/csharp/System.IO/Path/Combine/misc.csproj +++ b/snippets/csharp/System.IO/Path/Combine/misc.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable Program diff --git a/snippets/csharp/System.IO/Path/Combine/pathcombine.cs b/snippets/csharp/System.IO/Path/Combine/pathcombine.cs index 2088cc15b8d..c153c78a75b 100644 --- a/snippets/csharp/System.IO/Path/Combine/pathcombine.cs +++ b/snippets/csharp/System.IO/Path/Combine/pathcombine.cs @@ -2,40 +2,29 @@ using System; using System.IO; -public class ChangeExtensionTest { - - public static void Main() { - +public class ChangeExtensionTest +{ + public static void Main() + { string path1 = "c:\\temp"; string path2 = "subdir\\file.txt"; string path3 = "c:\\temp.txt"; string path4 = "c:^*&)(_=@#'\\^.*(.txt"; string path5 = ""; - string path6 = null; CombinePaths(path1, path2); CombinePaths(path1, path3); CombinePaths(path3, path2); CombinePaths(path4, path2); CombinePaths(path5, path2); - CombinePaths(path6, path2); } - private static void CombinePaths(string p1, string p2) { + private static void CombinePaths(string p1, string p2) + { + string combination = Path.Combine(p1, p2); - try { - string combination = Path.Combine(p1, p2); - - Console.WriteLine("When you combine '{0}' and '{1}', the result is: {2}'{3}'", - p1, p2, Environment.NewLine, combination); - } catch (Exception e) { - if (p1 == null) - p1 = "null"; - if (p2 == null) - p2 = "null"; - Console.WriteLine("You cannot combine '{0}' and '{1}' because: {2}{3}", - p1, p2, Environment.NewLine, e.Message); - } + Console.WriteLine("When you combine '{0}' and '{1}', the result is: {2}'{3}'", + p1, p2, Environment.NewLine, combination); Console.WriteLine(); } @@ -56,8 +45,4 @@ private static void CombinePaths(string p1, string p2) { // // When you combine '' and 'subdir\file.txt', the result is: // 'subdir\file.txt' -// -// You cannot combine 'null' and 'subdir\file.txt' because: -// Value cannot be null. -// Parameter name: path1 // diff --git a/snippets/csharp/System.IO/Path/DirectorySeparatorChar/directoryseparatorchar.csproj b/snippets/csharp/System.IO/Path/DirectorySeparatorChar/directoryseparatorchar.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.IO/Path/DirectorySeparatorChar/directoryseparatorchar.csproj +++ b/snippets/csharp/System.IO/Path/DirectorySeparatorChar/directoryseparatorchar.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.IO/Path/GetFullPath/getfullpath.csproj b/snippets/csharp/System.IO/Path/GetFullPath/getfullpath.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.IO/Path/GetFullPath/getfullpath.csproj +++ b/snippets/csharp/System.IO/Path/GetFullPath/getfullpath.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.IO/Path/IsPathRooted/ispathrooted.csproj b/snippets/csharp/System.IO/Path/IsPathRooted/ispathrooted.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.IO/Path/IsPathRooted/ispathrooted.csproj +++ b/snippets/csharp/System.IO/Path/IsPathRooted/ispathrooted.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.IO/Path/TryJoin/tryjoin.csproj b/snippets/csharp/System.IO/Path/TryJoin/tryjoin.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.IO/Path/TryJoin/tryjoin.csproj +++ b/snippets/csharp/System.IO/Path/TryJoin/tryjoin.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Net.Http/HttpClientHandler/Overview/system.net.http.httpclienthandler.csproj b/snippets/csharp/System.Net.Http/HttpClientHandler/Overview/system.net.http.httpclienthandler.csproj index ae63b11b4ec..85be5942ad1 100644 --- a/snippets/csharp/System.Net.Http/HttpClientHandler/Overview/system.net.http.httpclienthandler.csproj +++ b/snippets/csharp/System.Net.Http/HttpClientHandler/Overview/system.net.http.httpclienthandler.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable dotnet_api_docs diff --git a/snippets/csharp/System.Net.Http/HttpClientHandler/ServerCertificateCustomValidationCallback/program.cs b/snippets/csharp/System.Net.Http/HttpClientHandler/ServerCertificateCustomValidationCallback/program.cs index 9f90204bfdd..cc1f1abf4a9 100644 --- a/snippets/csharp/System.Net.Http/HttpClientHandler/ServerCertificateCustomValidationCallback/program.cs +++ b/snippets/csharp/System.Net.Http/HttpClientHandler/ServerCertificateCustomValidationCallback/program.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Net; using System.Net.Http; @@ -42,14 +42,14 @@ static async Task Main() client.Dispose(); } - private static bool ServerCertificateCustomValidation(HttpRequestMessage requestMessage, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslErrors) + private static bool ServerCertificateCustomValidation(HttpRequestMessage requestMessage, X509Certificate2? certificate, X509Chain? chain, SslPolicyErrors sslErrors) { // It is possible to inspect the certificate provided by the server. Console.WriteLine($"Requested URI: {requestMessage.RequestUri}"); - Console.WriteLine($"Effective date: {certificate.GetEffectiveDateString()}"); - Console.WriteLine($"Exp date: {certificate.GetExpirationDateString()}"); - Console.WriteLine($"Issuer: {certificate.Issuer}"); - Console.WriteLine($"Subject: {certificate.Subject}"); + Console.WriteLine($"Effective date: {certificate?.GetEffectiveDateString()}"); + Console.WriteLine($"Exp date: {certificate?.GetExpirationDateString()}"); + Console.WriteLine($"Issuer: {certificate?.Issuer}"); + Console.WriteLine($"Subject: {certificate?.Subject}"); // Based on the custom logic it is possible to decide whether the client considers certificate valid or not Console.WriteLine($"Errors: {sslErrors}"); diff --git a/snippets/csharp/System.Net.Http/HttpClientHandler/ServerCertificateCustomValidationCallback/system.net.http.httpclienthandler-secure.csproj b/snippets/csharp/System.Net.Http/HttpClientHandler/ServerCertificateCustomValidationCallback/system.net.http.httpclienthandler-secure.csproj index ae63b11b4ec..85be5942ad1 100644 --- a/snippets/csharp/System.Net.Http/HttpClientHandler/ServerCertificateCustomValidationCallback/system.net.http.httpclienthandler-secure.csproj +++ b/snippets/csharp/System.Net.Http/HttpClientHandler/ServerCertificateCustomValidationCallback/system.net.http.httpclienthandler-secure.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable dotnet_api_docs diff --git a/snippets/csharp/System.Net.Http/SocketsHttpHandler/ConnectCallback/system.net.http.httpclienthandler-secure.csproj b/snippets/csharp/System.Net.Http/SocketsHttpHandler/ConnectCallback/system.net.http.httpclienthandler-secure.csproj index ae63b11b4ec..85be5942ad1 100644 --- a/snippets/csharp/System.Net.Http/SocketsHttpHandler/ConnectCallback/system.net.http.httpclienthandler-secure.csproj +++ b/snippets/csharp/System.Net.Http/SocketsHttpHandler/ConnectCallback/system.net.http.httpclienthandler-secure.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable dotnet_api_docs diff --git a/snippets/csharp/System.Net.NetworkInformation/PhysicalAddress/Overview/NCLPhysicalAddress.csproj b/snippets/csharp/System.Net.NetworkInformation/PhysicalAddress/Overview/NCLPhysicalAddress.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.Net.NetworkInformation/PhysicalAddress/Overview/NCLPhysicalAddress.csproj +++ b/snippets/csharp/System.Net.NetworkInformation/PhysicalAddress/Overview/NCLPhysicalAddress.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Net.NetworkInformation/PhysicalAddress/Overview/physaddresstester.cs b/snippets/csharp/System.Net.NetworkInformation/PhysicalAddress/Overview/physaddresstester.cs index b2ec27d7743..a16099842a1 100644 --- a/snippets/csharp/System.Net.NetworkInformation/PhysicalAddress/Overview/physaddresstester.cs +++ b/snippets/csharp/System.Net.NetworkInformation/PhysicalAddress/Overview/physaddresstester.cs @@ -3,10 +3,9 @@ namespace Examples.System.Net.Networking { - public class PhysicalAddressExample { -// + // static void DisplayAddressNone() { PhysicalAddress none = PhysicalAddress.None; @@ -19,9 +18,9 @@ static void DisplayAddressNone() } Console.WriteLine(); } -// + // -// + // public static void ShowNetworkInterfaces() { IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties(); @@ -40,27 +39,27 @@ public static void ShowNetworkInterfaces() IPInterfaceProperties properties = adapter.GetIPProperties(); // .GetIPInterfaceProperties(); Console.WriteLine(); Console.WriteLine(adapter.Description); - Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length,'=')); + Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length, '=')); Console.WriteLine(" Interface type .......................... : {0}", adapter.NetworkInterfaceType); Console.Write(" Physical address ........................ : "); PhysicalAddress address = adapter.GetPhysicalAddress(); byte[] bytes = address.GetAddressBytes(); - for(int i = 0; i< bytes.Length; i++) + for (int i = 0; i < bytes.Length; i++) { // Display the physical address in hexadecimal. Console.Write("{0}", bytes[i].ToString("X2")); - // Insert a hyphen after each byte, unless we are at the end of the - // address. - if (i != bytes.Length -1) + // Insert a hyphen after each byte, unless we're at the end of the address. + if (i != bytes.Length - 1) { - Console.Write("-"); + Console.Write("-"); } } Console.WriteLine(); } } -// -// + // + + // public static void ParseTest() { PhysicalAddress address = PhysicalAddress.Parse("AC1EBA22"); @@ -70,9 +69,10 @@ public static void ParseTest() bool test = address.Equals(address2); Console.WriteLine("Equal? {0}", test); } -// -// - public static PhysicalAddress[] StoreNetworkInterfaceAddresses() + // + + // + public static PhysicalAddress[]? StoreNetworkInterfaceAddresses() { IPGlobalProperties computerProperties = IPGlobalProperties.GetIPGlobalProperties(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); @@ -89,14 +89,15 @@ public static PhysicalAddress[] StoreNetworkInterfaceAddresses() IPInterfaceProperties properties = adapter.GetIPProperties(); PhysicalAddress address = adapter.GetPhysicalAddress(); byte[] bytes = address.GetAddressBytes(); - PhysicalAddress newAddress = new PhysicalAddress(bytes); - addresses[i++]=newAddress; - } + PhysicalAddress newAddress = new PhysicalAddress(bytes); + addresses[i++] = newAddress; + } return addresses; } -// -// - public static PhysicalAddress StrictParseAddress(string address) + // + + // + public static PhysicalAddress? StrictParseAddress(string? address) { PhysicalAddress newAddress = PhysicalAddress.Parse(address); if (PhysicalAddress.None.Equals(newAddress)) @@ -104,10 +105,10 @@ public static PhysicalAddress StrictParseAddress(string address) return newAddress; } -// + // -// - public static PhysicalAddress StrictParseAddress(ReadOnlySpan address) + // + public static PhysicalAddress? StrictParseAddress(ReadOnlySpan address) { PhysicalAddress newAddress = PhysicalAddress.Parse(address); if (PhysicalAddress.None.Equals(newAddress)) @@ -115,24 +116,27 @@ public static PhysicalAddress StrictParseAddress(ReadOnlySpan address) return newAddress; } -// + // public static void Main() { - DisplayAddressNone(); - ShowNetworkInterfaces(); - ParseTest(); - PhysicalAddress[] addresses = StoreNetworkInterfaceAddresses(); - foreach (PhysicalAddress address in addresses) - { - Console.WriteLine(address.ToString()); - } + DisplayAddressNone(); + ShowNetworkInterfaces(); + ParseTest(); + PhysicalAddress[]? addresses = StoreNetworkInterfaceAddresses(); + if (addresses is not null) + { + foreach (PhysicalAddress address in addresses) + { + Console.WriteLine(address.ToString()); + } + } - PhysicalAddress a = StrictParseAddress((string)null); - Console.WriteLine(a?.ToString() ?? "null"); + PhysicalAddress? a = StrictParseAddress(null); + Console.WriteLine(a?.ToString() ?? "null"); - PhysicalAddress b = StrictParseAddress("".AsSpan()); - Console.WriteLine(b?.ToString() ?? "null"); + PhysicalAddress? b = StrictParseAddress("".AsSpan()); + Console.WriteLine(b?.ToString() ?? "null"); } } } diff --git a/snippets/csharp/System.Net.Sockets/Socket/Receive/Socket_Sync_Send_Receive.csproj b/snippets/csharp/System.Net.Sockets/Socket/Receive/Socket_Sync_Send_Receive.csproj index 1005954432e..bfc284cbd5b 100644 --- a/snippets/csharp/System.Net.Sockets/Socket/Receive/Socket_Sync_Send_Receive.csproj +++ b/snippets/csharp/System.Net.Sockets/Socket/Receive/Socket_Sync_Send_Receive.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable Sync_Send_Receive diff --git a/snippets/csharp/System.Net.Sockets/Socket/Receive/sendgeneric.cs b/snippets/csharp/System.Net.Sockets/Socket/Receive/sendgeneric.cs index a8a886f11dd..b85a0ddee27 100644 --- a/snippets/csharp/System.Net.Sockets/Socket/Receive/sendgeneric.cs +++ b/snippets/csharp/System.Net.Sockets/Socket/Receive/sendgeneric.cs @@ -8,7 +8,7 @@ namespace send_generics_csharp { class Class1 - { + { public static int syncSendAndReceive(string host, int port) { // @@ -16,12 +16,12 @@ public static int syncSendAndReceive(string host, int port) Encoding ASCII = Encoding.ASCII; // Create the TCP Socket. - IPHostEntry hostEntry = Dns.Resolve(host); + IPHostEntry hostEntry = Dns.GetHostEntry(host); IPEndPoint EPhost = new IPEndPoint( hostEntry.AddressList[0], port); Socket mySocket = new Socket(AddressFamily.InterNetwork, - SocketType.Stream, ProtocolType.Tcp ); + SocketType.Stream, ProtocolType.Tcp); mySocket.Connect(EPhost); @@ -51,13 +51,11 @@ public static int syncSendAndReceive(string host, int port) // Specify the first buffer segment (2 bytes, starting // at the 4th element of bigBuffer) - recvBuffers.Add(new ArraySegment - (bigBuffer, 4, 2)); + recvBuffers.Add(new ArraySegment(bigBuffer, 4, 2)); // Specify the second buffer segment (500 bytes, starting // at the 20th element of bigBuffer) - recvBuffers.Add(new ArraySegment - (bigBuffer, 20, 500)); + recvBuffers.Add(new ArraySegment(bigBuffer, 20, 500)); int bytesReceived = mySocket.Receive(recvBuffers); @@ -73,15 +71,17 @@ public static int syncSendAndReceive(string host, int port) public static void SendCallback(IAsyncResult ar) { allDone.Set(); - Socket s = (Socket) ar.AsyncState; - s.EndSend(ar); + if (ar.AsyncState is Socket s) + { + s.EndSend(ar); + } } public static void ReceiveCallback(IAsyncResult ar) { allDone.Set(); - Socket s = (Socket) ar.AsyncState; - s.EndReceive(ar); + Socket? s = (Socket?)ar.AsyncState; + s?.EndReceive(ar); } public static int asyncSendAndReceive(string host, int port) @@ -91,12 +91,12 @@ public static int asyncSendAndReceive(string host, int port) Encoding ASCII = Encoding.ASCII; // Create the TCP Socket. - IPHostEntry hostEntry = Dns.Resolve(host); + IPHostEntry hostEntry = Dns.GetHostEntry(host); IPEndPoint EPhost = new IPEndPoint( hostEntry.AddressList[0], port); Socket mySocket = new Socket(AddressFamily.InterNetwork, - SocketType.Stream, ProtocolType.Tcp ); + SocketType.Stream, ProtocolType.Tcp); mySocket.Connect(EPhost); @@ -150,7 +150,7 @@ public static int asyncSendAndReceive(string host, int port) Console.WriteLine("{0}", ASCII.GetString(bigBuffer)); // - return 1; + return 1; } [STAThread] diff --git a/snippets/csharp/System.Net.Sockets/Socket/Receive/source.cs b/snippets/csharp/System.Net.Sockets/Socket/Receive/source.cs index 4fc543d4e79..cb8f02e5df8 100644 --- a/snippets/csharp/System.Net.Sockets/Socket/Receive/source.cs +++ b/snippets/csharp/System.Net.Sockets/Socket/Receive/source.cs @@ -394,7 +394,7 @@ public static int Main(string[] args) // Send or receive the test messages. if (isServer) { - Socket sender = null; + Socket? sender; s.Bind(endPoint); s.Listen(1); while (true) diff --git a/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/TcpClient.csproj b/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/TcpClient.csproj index adbde6e0619..d260053fe00 100644 --- a/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/TcpClient.csproj +++ b/snippets/csharp/System.Net.Sockets/TcpClient/.ctor/TcpClient.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable \ No newline at end of file diff --git a/snippets/csharp/System.Reflection.Emit/AssemblyBuilder/Overview/24895.cs b/snippets/csharp/System.Reflection.Emit/AssemblyBuilder/Overview/24895.cs index 93744ae02da..69bf416f7b0 100644 --- a/snippets/csharp/System.Reflection.Emit/AssemblyBuilder/Overview/24895.cs +++ b/snippets/csharp/System.Reflection.Emit/AssemblyBuilder/Overview/24895.cs @@ -1,4 +1,4 @@ -// +// using System; using System.Reflection; using System.Reflection.Emit; @@ -37,15 +37,14 @@ public int MyMethod(int multiplier) } */ - AssemblyName aName = new AssemblyName("DynamicAssemblyExample"); + var aName = new AssemblyName("DynamicAssemblyExample"); AssemblyBuilder ab = AssemblyBuilder.DefineDynamicAssembly( aName, AssemblyBuilderAccess.Run); // The module name is usually the same as the assembly name. - ModuleBuilder mb = - ab.DefineDynamicModule(aName.Name); + ModuleBuilder mb = ab.DefineDynamicModule(aName.Name ?? "DynamicAssemblyExample"); TypeBuilder tb = mb.DefineType( "MyDynamicType", @@ -72,8 +71,8 @@ public int MyMethod(int multiplier) // base class (System.Object) by passing an empty array of // types (Type.EmptyTypes) to GetConstructor. ctor1IL.Emit(OpCodes.Ldarg_0); - ctor1IL.Emit(OpCodes.Call, - typeof(object).GetConstructor(Type.EmptyTypes)); + ConstructorInfo? ci = typeof(object).GetConstructor(Type.EmptyTypes); + ctor1IL.Emit(OpCodes.Call, ci!); // Push the instance on the stack before pushing the argument // that is to be assigned to the private field m_number. ctor1IL.Emit(OpCodes.Ldarg_0); @@ -176,40 +175,43 @@ public int MyMethod(int multiplier) methIL.Emit(OpCodes.Ret); // Finish the type. - Type t = tb.CreateType(); + Type? t = tb.CreateType(); // Because AssemblyBuilderAccess includes Run, the code can be // executed immediately. Start by getting reflection objects for // the method and the property. - MethodInfo mi = t.GetMethod("MyMethod"); - PropertyInfo pi = t.GetProperty("Number"); + MethodInfo? mi = t?.GetMethod("MyMethod"); + PropertyInfo? pi = t?.GetProperty("Number"); // Create an instance of MyDynamicType using the default // constructor. - object o1 = Activator.CreateInstance(t); + object? o1 = null; + if (t is not null) + o1 = Activator.CreateInstance(t); // Display the value of the property, then change it to 127 and // display it again. Use null to indicate that the property // has no index. - Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, null)); - pi.SetValue(o1, 127, null); - Console.WriteLine("o1.Number: {0}", pi.GetValue(o1, null)); + Console.WriteLine("o1.Number: {0}", pi?.GetValue(o1, null)); + pi?.SetValue(o1, 127, null); + Console.WriteLine("o1.Number: {0}", pi?.GetValue(o1, null)); // Call MyMethod, passing 22, and display the return value, 22 // times 127. Arguments must be passed as an array, even when // there is only one. object[] arguments = { 22 }; Console.WriteLine("o1.MyMethod(22): {0}", - mi.Invoke(o1, arguments)); + mi?.Invoke(o1, arguments)); // Create an instance of MyDynamicType using the constructor // that specifies m_Number. The constructor is identified by // matching the types in the argument array. In this case, // the argument array is created on the fly. Display the // property value. - object o2 = Activator.CreateInstance(t, - new object[] { 5280 }); - Console.WriteLine("o2.Number: {0}", pi.GetValue(o2, null)); + object? o2 = null; + if (t is not null) + Activator.CreateInstance(t, new object[] { 5280 }); + Console.WriteLine("o2.Number: {0}", pi?.GetValue(o2, null)); } } diff --git a/snippets/csharp/System.Reflection.Emit/AssemblyBuilder/Overview/AssemblyBuilderClass.csproj b/snippets/csharp/System.Reflection.Emit/AssemblyBuilder/Overview/AssemblyBuilderClass.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.Reflection.Emit/AssemblyBuilder/Overview/AssemblyBuilderClass.csproj +++ b/snippets/csharp/System.Reflection.Emit/AssemblyBuilder/Overview/AssemblyBuilderClass.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Reflection.Emit/FieldBuilder/Overview/FieldBuilder.cs b/snippets/csharp/System.Reflection.Emit/FieldBuilder/Overview/FieldBuilder.cs index 72387cf4cbb..ae046ca966c 100644 --- a/snippets/csharp/System.Reflection.Emit/FieldBuilder/Overview/FieldBuilder.cs +++ b/snippets/csharp/System.Reflection.Emit/FieldBuilder/Overview/FieldBuilder.cs @@ -4,63 +4,66 @@ public class FieldBuilder_Sample { - private static Type CreateType() - { - // Create an assembly. - AssemblyName assemName = new AssemblyName(); - assemName.Name = "DynamicAssembly"; - AssemblyBuilder assemBuilder = - AssemblyBuilder.DefineDynamicAssembly(assemName, AssemblyBuilderAccess.Run); - // Create a dynamic module in Dynamic Assembly. - ModuleBuilder modBuilder = assemBuilder.DefineDynamicModule("DynamicModule"); - // Define a public class named "DynamicClass" in the assembly. - TypeBuilder typBuilder = modBuilder.DefineType("DynamicClass", TypeAttributes.Public); + private static Type? CreateType() + { + // Create an assembly. + AssemblyName assemName = new AssemblyName(); + assemName.Name = "DynamicAssembly"; + AssemblyBuilder assemBuilder = + AssemblyBuilder.DefineDynamicAssembly(assemName, AssemblyBuilderAccess.Run); + // Create a dynamic module in Dynamic Assembly. + ModuleBuilder modBuilder = assemBuilder.DefineDynamicModule("DynamicModule"); + // Define a public class named "DynamicClass" in the assembly. + TypeBuilder typBuilder = modBuilder.DefineType("DynamicClass", TypeAttributes.Public); - // Define a private String field named "DynamicField" in the type. - FieldBuilder fldBuilder = typBuilder.DefineField("DynamicField", - typeof(string), FieldAttributes.Private | FieldAttributes.Static); - // Create the constructor. - Type[] constructorArgs = { typeof(String) }; - ConstructorBuilder constructor = typBuilder.DefineConstructor( - MethodAttributes.Public, CallingConventions.Standard, constructorArgs); - ILGenerator constructorIL = constructor.GetILGenerator(); - constructorIL.Emit(OpCodes.Ldarg_0); - ConstructorInfo superConstructor = typeof(Object).GetConstructor(new Type[0]); - constructorIL.Emit(OpCodes.Call, superConstructor); - constructorIL.Emit(OpCodes.Ldarg_0); - constructorIL.Emit(OpCodes.Ldarg_1); - constructorIL.Emit(OpCodes.Stfld, fldBuilder); - constructorIL.Emit(OpCodes.Ret); + // Define a private String field named "DynamicField" in the type. + FieldBuilder fldBuilder = typBuilder.DefineField("DynamicField", + typeof(string), FieldAttributes.Private | FieldAttributes.Static); + // Create the constructor. + Type[] constructorArgs = { typeof(String) }; + ConstructorBuilder constructor = typBuilder.DefineConstructor( + MethodAttributes.Public, CallingConventions.Standard, constructorArgs); + ILGenerator constructorIL = constructor.GetILGenerator(); + constructorIL.Emit(OpCodes.Ldarg_0); + ConstructorInfo? superConstructor = typeof(Object).GetConstructor(new Type[0]); + constructorIL.Emit(OpCodes.Call, superConstructor!); + constructorIL.Emit(OpCodes.Ldarg_0); + constructorIL.Emit(OpCodes.Ldarg_1); + constructorIL.Emit(OpCodes.Stfld, fldBuilder); + constructorIL.Emit(OpCodes.Ret); - // Create the DynamicMethod method. - MethodBuilder methBuilder= typBuilder.DefineMethod("DynamicMethod", - MethodAttributes.Public,typeof(String),null); - ILGenerator methodIL = methBuilder.GetILGenerator(); - methodIL.Emit(OpCodes.Ldarg_0); - methodIL.Emit(OpCodes.Ldfld, fldBuilder); - methodIL.Emit(OpCodes.Ret); + // Create the DynamicMethod method. + MethodBuilder methBuilder = typBuilder.DefineMethod("DynamicMethod", + MethodAttributes.Public, typeof(String), null); + ILGenerator methodIL = methBuilder.GetILGenerator(); + methodIL.Emit(OpCodes.Ldarg_0); + methodIL.Emit(OpCodes.Ldfld, fldBuilder); + methodIL.Emit(OpCodes.Ret); - Console.WriteLine($"Name : {fldBuilder.Name}"); - Console.WriteLine($"DeclaringType : {fldBuilder.DeclaringType}"); - Console.WriteLine($"Type : {fldBuilder.FieldType}"); - return typBuilder.CreateType(); - } + Console.WriteLine($"Name : {fldBuilder.Name}"); + Console.WriteLine($"DeclaringType : {fldBuilder.DeclaringType}"); + Console.WriteLine($"Type : {fldBuilder.FieldType}"); + return typBuilder.CreateType(); + } - public static void Main() - { - Type dynType = CreateType(); - try - { - // Create an instance of the "HelloWorld" class. - Object helloWorld = Activator.CreateInstance(dynType, new Object[] { "HelloWorld" }); - // Invoke the "DynamicMethod" method of the "DynamicClass" class. - Object obj = dynType.InvokeMember("DynamicMethod", - BindingFlags.InvokeMethod, null, helloWorld, null); - Console.WriteLine($"DynamicClass.DynamicMethod returned: \"{obj}\""); - } - catch(MethodAccessException e) - { - Console.WriteLine($"{e.GetType().Name}: {e.Message}"); - } - } -} \ No newline at end of file + public static void Main() + { + Type? dynType = CreateType(); + try + { + if (dynType is not null) + { + // Create an instance of the "HelloWorld" class. + Object? helloWorld = Activator.CreateInstance(dynType, new Object[] { "HelloWorld" }); + // Invoke the "DynamicMethod" method of the "DynamicClass" class. + Object? obj = dynType.InvokeMember("DynamicMethod", + BindingFlags.InvokeMethod, null, helloWorld, null); + Console.WriteLine($"DynamicClass.DynamicMethod returned: \"{obj}\""); + } + } + catch (MethodAccessException e) + { + Console.WriteLine($"{e.GetType().Name}: {e.Message}"); + } + } +} diff --git a/snippets/csharp/System.Reflection.Emit/FieldBuilder/Overview/FieldBuilder.csproj b/snippets/csharp/System.Reflection.Emit/FieldBuilder/Overview/FieldBuilder.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.Reflection.Emit/FieldBuilder/Overview/FieldBuilder.csproj +++ b/snippets/csharp/System.Reflection.Emit/FieldBuilder/Overview/FieldBuilder.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Reflection.Metadata.Ecma335/BlobEncoder/MethodSignature/MethodSignatureSnippets.csproj b/snippets/csharp/System.Reflection.Metadata.Ecma335/BlobEncoder/MethodSignature/MethodSignatureSnippets.csproj index ddb344e65f4..8abc7def008 100644 --- a/snippets/csharp/System.Reflection.Metadata.Ecma335/BlobEncoder/MethodSignature/MethodSignatureSnippets.csproj +++ b/snippets/csharp/System.Reflection.Metadata.Ecma335/BlobEncoder/MethodSignature/MethodSignatureSnippets.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Reflection.Metadata.Ecma335/ControlFlowBuilder/Overview/ControlFlowBuilderSnippets.csproj b/snippets/csharp/System.Reflection.Metadata.Ecma335/ControlFlowBuilder/Overview/ControlFlowBuilderSnippets.csproj index ddb344e65f4..8abc7def008 100644 --- a/snippets/csharp/System.Reflection.Metadata.Ecma335/ControlFlowBuilder/Overview/ControlFlowBuilderSnippets.csproj +++ b/snippets/csharp/System.Reflection.Metadata.Ecma335/ControlFlowBuilder/Overview/ControlFlowBuilderSnippets.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Reflection.Metadata.Ecma335/InstructionEncoder/Overview/InstructionEncoderSnippets.csproj b/snippets/csharp/System.Reflection.Metadata.Ecma335/InstructionEncoder/Overview/InstructionEncoderSnippets.csproj index ddb344e65f4..8abc7def008 100644 --- a/snippets/csharp/System.Reflection.Metadata.Ecma335/InstructionEncoder/Overview/InstructionEncoderSnippets.csproj +++ b/snippets/csharp/System.Reflection.Metadata.Ecma335/InstructionEncoder/Overview/InstructionEncoderSnippets.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Reflection.Metadata.Ecma335/MetadataBuilder/MetadataBuilderSnippets.csproj b/snippets/csharp/System.Reflection.Metadata.Ecma335/MetadataBuilder/MetadataBuilderSnippets.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.Reflection.Metadata.Ecma335/MetadataBuilder/MetadataBuilderSnippets.csproj +++ b/snippets/csharp/System.Reflection.Metadata.Ecma335/MetadataBuilder/MetadataBuilderSnippets.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Reflection.Metadata/Document/DocumentSnippets.csproj b/snippets/csharp/System.Reflection.Metadata/Document/DocumentSnippets.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.Reflection.Metadata/Document/DocumentSnippets.csproj +++ b/snippets/csharp/System.Reflection.Metadata/Document/DocumentSnippets.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Reflection.Metadata/Document/Program.cs b/snippets/csharp/System.Reflection.Metadata/Document/Program.cs index ec4fc599cd0..826a7192c9b 100644 --- a/snippets/csharp/System.Reflection.Metadata/Document/Program.cs +++ b/snippets/csharp/System.Reflection.Metadata/Document/Program.cs @@ -7,8 +7,11 @@ class Program { static void Main(string[] args) { - string pdbPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location),"DocumentSnippets.pdb"); - DocumentSnippets.ReadPdbDocuments(pdbPath); + if (Path.GetDirectoryName(typeof(Program).Assembly.Location) is string loc) + { + string pdbPath = Path.Combine(loc, "DocumentSnippets.pdb"); + DocumentSnippets.ReadPdbDocuments(pdbPath); + } } } } diff --git a/snippets/csharp/System.Reflection.Metadata/MetadataReader/MetadataReaderSnippets.csproj b/snippets/csharp/System.Reflection.Metadata/MetadataReader/MetadataReaderSnippets.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.Reflection.Metadata/MetadataReader/MetadataReaderSnippets.csproj +++ b/snippets/csharp/System.Reflection.Metadata/MetadataReader/MetadataReaderSnippets.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Reflection.Metadata/MethodBodyBlock/MethodBodyBlockSnippets.cs b/snippets/csharp/System.Reflection.Metadata/MethodBodyBlock/MethodBodyBlockSnippets.cs index c12940bfc60..11ecc8eb29f 100644 --- a/snippets/csharp/System.Reflection.Metadata/MethodBodyBlock/MethodBodyBlockSnippets.cs +++ b/snippets/csharp/System.Reflection.Metadata/MethodBodyBlock/MethodBodyBlockSnippets.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Reflection.Metadata; using System.Reflection.PortableExecutable; @@ -33,8 +33,8 @@ static void PrintMethods(PEReader reader, MetadataReader mr, TypeDefinition tdef Console.WriteLine($" Maximum stack size: {mb.MaxStack}"); Console.WriteLine($" Local variables initialized: {mb.LocalVariablesInitialized}"); - byte[] il = mb.GetILBytes(); - Console.WriteLine($" Method body size: {il.Length}"); + byte[]? il = mb.GetILBytes(); + Console.WriteLine($" Method body size: {il?.Length ?? 0}"); Console.WriteLine($" Exception regions: {mb.ExceptionRegions.Length}"); Console.WriteLine(); @@ -55,7 +55,7 @@ public static void Run() { string path = typeof(Program).Assembly.Location; using var s = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); - using var reader = new PEReader(s); + using var reader = new PEReader(s); MetadataReader mr = reader.GetMetadataReader(MetadataReaderOptions.None); foreach (TypeDefinitionHandle t in mr.TypeDefinitions) diff --git a/snippets/csharp/System.Reflection.Metadata/MethodBodyBlock/MethodBodyBlockSnippets.csproj b/snippets/csharp/System.Reflection.Metadata/MethodBodyBlock/MethodBodyBlockSnippets.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.Reflection.Metadata/MethodBodyBlock/MethodBodyBlockSnippets.csproj +++ b/snippets/csharp/System.Reflection.Metadata/MethodBodyBlock/MethodBodyBlockSnippets.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Reflection.Metadata/SequencePoint/Overview/Program.cs b/snippets/csharp/System.Reflection.Metadata/SequencePoint/Overview/Program.cs index 1e4181afff8..0609ecabab0 100644 --- a/snippets/csharp/System.Reflection.Metadata/SequencePoint/Overview/Program.cs +++ b/snippets/csharp/System.Reflection.Metadata/SequencePoint/Overview/Program.cs @@ -8,8 +8,13 @@ class Program { static void Main(string[] args) { - string pdbPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "SequencePointSnippets.pdb"); - SequencePointSnippets.ReadSourceLineData(pdbPath, MethodInfo.GetCurrentMethod().MetadataToken); + if (Path.GetDirectoryName(typeof(Program).Assembly.Location) is string loc) + { + string pdbPath = Path.Combine(loc, "SequencePointSnippets.pdb"); + + if (MethodInfo.GetCurrentMethod() is MethodBase mbase) + SequencePointSnippets.ReadSourceLineData(pdbPath, mbase.MetadataToken); + } } } } diff --git a/snippets/csharp/System.Reflection.Metadata/SequencePoint/Overview/SequencePointSnippets.cs b/snippets/csharp/System.Reflection.Metadata/SequencePoint/Overview/SequencePointSnippets.cs index 0da55da0079..dde0da18fda 100644 --- a/snippets/csharp/System.Reflection.Metadata/SequencePoint/Overview/SequencePointSnippets.cs +++ b/snippets/csharp/System.Reflection.Metadata/SequencePoint/Overview/SequencePointSnippets.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.IO; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; diff --git a/snippets/csharp/System.Reflection.Metadata/SequencePoint/Overview/SequencePointSnippets.csproj b/snippets/csharp/System.Reflection.Metadata/SequencePoint/Overview/SequencePointSnippets.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.Reflection.Metadata/SequencePoint/Overview/SequencePointSnippets.csproj +++ b/snippets/csharp/System.Reflection.Metadata/SequencePoint/Overview/SequencePointSnippets.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Reflection.PortableExecutable/PEHeader/Overview/PEHeaderSnippets.cs b/snippets/csharp/System.Reflection.PortableExecutable/PEHeader/Overview/PEHeaderSnippets.cs index 8337425dbcc..86054a1d10b 100644 --- a/snippets/csharp/System.Reflection.PortableExecutable/PEHeader/Overview/PEHeaderSnippets.cs +++ b/snippets/csharp/System.Reflection.PortableExecutable/PEHeader/Overview/PEHeaderSnippets.cs @@ -14,15 +14,17 @@ static void ExampleReadPEHeader() using var peReader = new PEReader(fs); // Display PE header information - PEHeader header = peReader.PEHeaders.PEHeader; - Console.WriteLine($"Image size, bytes: {header.SizeOfImage}"); - Console.WriteLine($"Image base: 0x{header.ImageBase:X}"); - Console.WriteLine($"File alignment: 0x{header.FileAlignment:X}"); - Console.WriteLine($"Section alignment: 0x{header.SectionAlignment:X}"); - Console.WriteLine($"Subsystem: {header.Subsystem}"); - Console.WriteLine($"Dll characteristics: {header.DllCharacteristics}"); - Console.WriteLine($"Linker version: {header.MajorLinkerVersion}.{header.MinorLinkerVersion}"); - Console.WriteLine($"OS version: {header.MajorOperatingSystemVersion}.{header.MinorOperatingSystemVersion}"); + if (peReader.PEHeaders.PEHeader is PEHeader header) + { + Console.WriteLine($"Image size, bytes: {header.SizeOfImage}"); + Console.WriteLine($"Image base: 0x{header.ImageBase:X}"); + Console.WriteLine($"File alignment: 0x{header.FileAlignment:X}"); + Console.WriteLine($"Section alignment: 0x{header.SectionAlignment:X}"); + Console.WriteLine($"Subsystem: {header.Subsystem}"); + Console.WriteLine($"Dll characteristics: {header.DllCharacteristics}"); + Console.WriteLine($"Linker version: {header.MajorLinkerVersion}.{header.MinorLinkerVersion}"); + Console.WriteLine($"OS version: {header.MajorOperatingSystemVersion}.{header.MinorOperatingSystemVersion}"); + } // } diff --git a/snippets/csharp/System.Reflection.PortableExecutable/PEHeader/Overview/PEHeaderSnippets.csproj b/snippets/csharp/System.Reflection.PortableExecutable/PEHeader/Overview/PEHeaderSnippets.csproj index 120e38c3150..8c8d40ddc3a 100644 --- a/snippets/csharp/System.Reflection.PortableExecutable/PEHeader/Overview/PEHeaderSnippets.csproj +++ b/snippets/csharp/System.Reflection.PortableExecutable/PEHeader/Overview/PEHeaderSnippets.csproj @@ -3,6 +3,7 @@ Exe net7.0 + enable diff --git a/snippets/csharp/System.Reflection/EventInfo/AddEventHandler/cs.csproj b/snippets/csharp/System.Reflection/EventInfo/AddEventHandler/cs.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.Reflection/EventInfo/AddEventHandler/cs.csproj +++ b/snippets/csharp/System.Reflection/EventInfo/AddEventHandler/cs.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Reflection/EventInfo/AddEventHandler/source.cs b/snippets/csharp/System.Reflection/EventInfo/AddEventHandler/source.cs index 272e881eafd..7d994d018df 100644 --- a/snippets/csharp/System.Reflection/EventInfo/AddEventHandler/source.cs +++ b/snippets/csharp/System.Reflection/EventInfo/AddEventHandler/source.cs @@ -4,7 +4,7 @@ public class Example { - private static object timer; + private static object? timer; public static void Main() { @@ -14,7 +14,7 @@ public static void Main() timer = Activator.CreateInstance(t); // Use reflection to get the Elapsed event. - EventInfo eInfo = t.GetEvent("Elapsed"); + EventInfo? eInfo = t.GetEvent("Elapsed"); // In order to create a method to handle the Elapsed event, // it is necessary to know the signature of the delegate @@ -28,11 +28,11 @@ public static void Main() // creates an array of Type objects that represent the // parameter types of the Invoke method. // - Type handlerType = eInfo.EventHandlerType; - MethodInfo invokeMethod = handlerType.GetMethod("Invoke"); - ParameterInfo[] parms = invokeMethod.GetParameters(); - Type[] parmTypes = new Type[parms.Length]; - for (int i = 0; i < parms.Length; i++) + Type? handlerType = eInfo?.EventHandlerType; + MethodInfo? invokeMethod = handlerType?.GetMethod("Invoke"); + ParameterInfo[]? parms = invokeMethod?.GetParameters(); + Type[] parmTypes = new Type[parms?.Length ?? 0]; + for (int i = 0; i < parms?.Length; i++) { parmTypes[i] = parms[i].ParameterType; } @@ -60,7 +60,7 @@ public static void Main() // captured earlier. MethodBuilder handler = tb.DefineMethod("DynamicHandler", MethodAttributes.Public | MethodAttributes.Static, - invokeMethod.ReturnType, parmTypes); + invokeMethod?.ReturnType, parmTypes); // Generate code to handle the event. In this case, the // handler simply prints a text string to the console. @@ -73,14 +73,17 @@ public static void Main() // be used. In order to create the delegate that will // handle the event, a MethodInfo from the finished type // is required. - Type finished = tb.CreateType(); - MethodInfo eventHandler = finished.GetMethod("DynamicHandler"); + Type? finished = tb.CreateType(); + MethodInfo? eventHandler = finished?.GetMethod("DynamicHandler"); // Use the MethodInfo to create a delegate of the correct // type, and call the AddEventHandler method to hook up // the event. - Delegate d = Delegate.CreateDelegate(handlerType, eventHandler); - eInfo.AddEventHandler(timer, d); + if (handlerType is not null && eventHandler is not null) + { + Delegate d = Delegate.CreateDelegate(handlerType, eventHandler); + eInfo?.AddEventHandler(timer, d); + } // Late-bound calls to the Interval and Enabled property // are required to enable the timer with a one-second diff --git a/snippets/csharp/System.Runtime.CompilerServices/CallerFilePathAttribute/Project.csproj b/snippets/csharp/System.Runtime.CompilerServices/CallerFilePathAttribute/Project.csproj index 9ab42fef7a0..c014d56d0a3 100644 --- a/snippets/csharp/System.Runtime.CompilerServices/CallerFilePathAttribute/Project.csproj +++ b/snippets/csharp/System.Runtime.CompilerServices/CallerFilePathAttribute/Project.csproj @@ -3,6 +3,7 @@ Library net6.0 + enable diff --git a/snippets/csharp/System.Runtime.InteropServices/Attributes/Attributes.csproj b/snippets/csharp/System.Runtime.InteropServices/Attributes/Attributes.csproj index 07f5f167f18..8f2e93906d3 100644 --- a/snippets/csharp/System.Runtime.InteropServices/Attributes/Attributes.csproj +++ b/snippets/csharp/System.Runtime.InteropServices/Attributes/Attributes.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable true diff --git a/snippets/csharp/System.Runtime.InteropServices/Marshal/GetLastPInvokeError/Marshal.csproj b/snippets/csharp/System.Runtime.InteropServices/Marshal/GetLastPInvokeError/Marshal.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.Runtime.InteropServices/Marshal/GetLastPInvokeError/Marshal.csproj +++ b/snippets/csharp/System.Runtime.InteropServices/Marshal/GetLastPInvokeError/Marshal.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Text/Rune/Overview/RuneSamples.csproj b/snippets/csharp/System.Text/Rune/Overview/RuneSamples.csproj index 41f1d5ad4b2..1d22a369970 100644 --- a/snippets/csharp/System.Text/Rune/Overview/RuneSamples.csproj +++ b/snippets/csharp/System.Text/Rune/Overview/RuneSamples.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System.Threading/CountdownEvent/Overview/countdownevent.csproj b/snippets/csharp/System.Threading/CountdownEvent/Overview/countdownevent.csproj index 74954604db7..1d22a369970 100644 --- a/snippets/csharp/System.Threading/CountdownEvent/Overview/countdownevent.csproj +++ b/snippets/csharp/System.Threading/CountdownEvent/Overview/countdownevent.csproj @@ -1,8 +1,9 @@ - + Exe net6.0 + enable diff --git a/snippets/csharp/System/ArgumentOutOfRangeException/Overview/Race1.cs b/snippets/csharp/System/ArgumentOutOfRangeException/Overview/Race1.cs index f69a6d31dbb..b07903dd524 100644 --- a/snippets/csharp/System/ArgumentOutOfRangeException/Overview/Race1.cs +++ b/snippets/csharp/System/ArgumentOutOfRangeException/Overview/Race1.cs @@ -5,7 +5,7 @@ public class Continent { - public string Name { get; set; } + public string? Name { get; set; } public int Population { get; set; } public Decimal Area { get; set; } } @@ -13,7 +13,7 @@ public class Continent public class Example11 { static List continents = new List(); - static string msg; + static string? s_msg; public static void Main() { @@ -25,7 +25,7 @@ public static void Main() var th = new Thread(PopulateContinents); th.Start(name); } - Console.WriteLine(msg); + Console.WriteLine(s_msg); Console.WriteLine(); // Display the list. @@ -37,10 +37,10 @@ public static void Main() } } - private static void PopulateContinents(Object obj) + private static void PopulateContinents(Object? obj) { - string name = obj.ToString(); - msg += string.Format("Adding '{0}' to the list.\n", name); + string? name = obj?.ToString(); + s_msg += string.Format("Adding '{0}' to the list.\n", name); var continent = new Continent(); continent.Name = name; // Sleep to simulate retrieving remaining data. diff --git a/snippets/csharp/System/ArgumentOutOfRangeException/Overview/Race2.cs b/snippets/csharp/System/ArgumentOutOfRangeException/Overview/Race2.cs index 50aa91fead8..7d95070b30c 100644 --- a/snippets/csharp/System/ArgumentOutOfRangeException/Overview/Race2.cs +++ b/snippets/csharp/System/ArgumentOutOfRangeException/Overview/Race2.cs @@ -5,7 +5,7 @@ public class ContinentD { - public string Name { get; set; } + public string? Name { get; set; } public int Population { get; set; } public Decimal Area { get; set; } } @@ -13,7 +13,7 @@ public class ContinentD public class Example12 { static ConcurrentBag ContinentDs = new ConcurrentBag(); - static CountdownEvent gate; + static CountdownEvent? gate; static string msg = string.Empty; public static void Main() @@ -43,9 +43,9 @@ public static void Main() } } - private static void PopulateContinentDs(Object obj) + private static void PopulateContinentDs(Object? obj) { - string name = obj.ToString(); + string? name = obj?.ToString(); lock(msg) { msg += string.Format("Adding '{0}' to the list.\n", name); } @@ -54,7 +54,7 @@ private static void PopulateContinentDs(Object obj) // Sleep to simulate retrieving remaining data. Thread.Sleep(25); ContinentDs.Add(ContinentD); - gate.Signal(); + gate?.Signal(); } } // The example displays output like the following: diff --git a/snippets/csharp/System/ArgumentOutOfRangeException/Overview/cs.csproj b/snippets/csharp/System/ArgumentOutOfRangeException/Overview/cs.csproj index 5080ad5bdb8..21981895620 100644 --- a/snippets/csharp/System/ArgumentOutOfRangeException/Overview/cs.csproj +++ b/snippets/csharp/System/ArgumentOutOfRangeException/Overview/cs.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable Program diff --git a/snippets/csharp/System/DateTime/ToString/tostring.csproj b/snippets/csharp/System/DateTime/ToString/tostring.csproj index 11867364f3e..c645c6b0fbb 100644 --- a/snippets/csharp/System/DateTime/ToString/tostring.csproj +++ b/snippets/csharp/System/DateTime/ToString/tostring.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable MainClass diff --git a/snippets/csharp/System/Decimal/Round/Rounding.csproj b/snippets/csharp/System/Decimal/Round/Rounding.csproj index b906551488a..1508cc21dc1 100644 --- a/snippets/csharp/System/Decimal/Round/Rounding.csproj +++ b/snippets/csharp/System/Decimal/Round/Rounding.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable Example diff --git a/snippets/csharp/System/GC/SuppressFinalize/system.gc.suppressfinalize.csproj b/snippets/csharp/System/GC/SuppressFinalize/system.gc.suppressfinalize.csproj index 51e7359d501..00b1ba25da0 100644 --- a/snippets/csharp/System/GC/SuppressFinalize/system.gc.suppressfinalize.csproj +++ b/snippets/csharp/System/GC/SuppressFinalize/system.gc.suppressfinalize.csproj @@ -2,6 +2,7 @@ net6.0 + enable diff --git a/snippets/csharp/System/IDisposable/Overview/Dispose.csproj b/snippets/csharp/System/IDisposable/Overview/Dispose.csproj index 51e7359d501..00b1ba25da0 100644 --- a/snippets/csharp/System/IDisposable/Overview/Dispose.csproj +++ b/snippets/csharp/System/IDisposable/Overview/Dispose.csproj @@ -2,6 +2,7 @@ net6.0 + enable diff --git a/snippets/csharp/System/IDisposable/Overview/calling2.cs b/snippets/csharp/System/IDisposable/Overview/calling2.cs index e60083fc443..f8125236c6b 100644 --- a/snippets/csharp/System/IDisposable/Overview/calling2.cs +++ b/snippets/csharp/System/IDisposable/Overview/calling2.cs @@ -16,7 +16,7 @@ public WordCount2(string filename) this.filename = filename; string txt = String.Empty; - StreamReader sr = null; + StreamReader? sr = null; try { sr = new StreamReader(filename); diff --git a/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/cs.csproj b/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/cs.csproj index 07f5f167f18..8f2e93906d3 100644 --- a/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/cs.csproj +++ b/snippets/csharp/System/ReadOnlySpanT/GetPinnableReference/cs.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable true diff --git a/snippets/csharp/System/Span.Enumerator/synchronization.csproj b/snippets/csharp/System/Span.Enumerator/synchronization.csproj index 5080ad5bdb8..21981895620 100644 --- a/snippets/csharp/System/Span.Enumerator/synchronization.csproj +++ b/snippets/csharp/System/Span.Enumerator/synchronization.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable Program diff --git a/snippets/csharp/System/Span/Overview/program.csproj b/snippets/csharp/System/Span/Overview/program.csproj index c842a751b30..ba51a80bfe0 100644 --- a/snippets/csharp/System/Span/Overview/program.csproj +++ b/snippets/csharp/System/Span/Overview/program.csproj @@ -4,6 +4,7 @@ true Exe net6.0 + enable Latest diff --git a/snippets/csharp/System/Span/Slice/Program2.cs b/snippets/csharp/System/Span/Slice/Program2.cs index f5042440d4f..75bfaeff52a 100644 --- a/snippets/csharp/System/Span/Slice/Program2.cs +++ b/snippets/csharp/System/Span/Slice/Program2.cs @@ -2,7 +2,7 @@ class Program2 { - static void Main() + static void Run() { string contentLength = "Content-Length: 132"; var length = GetContentLength(contentLength.ToCharArray()); diff --git a/snippets/csharp/System/Span/Slice/slice.csproj b/snippets/csharp/System/Span/Slice/slice.csproj index 743bb28d34f..649ae14631d 100644 --- a/snippets/csharp/System/Span/Slice/slice.csproj +++ b/snippets/csharp/System/Span/Slice/slice.csproj @@ -3,5 +3,6 @@ Exe net6.0 + enable diff --git a/snippets/csharp/System/String/Compare/ArrayListSample.cs b/snippets/csharp/System/String/Compare/ArrayListSample.cs index 2e357f6169d..d85c1ff9a0d 100644 --- a/snippets/csharp/System/String/Compare/ArrayListSample.cs +++ b/snippets/csharp/System/String/Compare/ArrayListSample.cs @@ -3,61 +3,67 @@ using System.Text; using System.Collections; -public class SamplesArrayList { +public class SamplesArrayList +{ - public static void Main() { - // - // Creates and initializes a new ArrayList. - ArrayList myAL = new ArrayList(); - myAL.Add("Eric"); - myAL.Add("Mark"); - myAL.Add("Lance"); - myAL.Add("Rob"); - myAL.Add("Kris"); - myAL.Add("Brad"); - myAL.Add("Kit"); - myAL.Add("Bradley"); - myAL.Add("Keith"); - myAL.Add("Susan"); - - // Displays the properties and values of the ArrayList. - Console.WriteLine( "Count: {0}", myAL.Count ); - // - - PrintValues ("Unsorted", myAL ); - // - myAL.Sort(); - PrintValues("Sorted", myAL ); - // - // - myAL.Sort(new ReverseStringComparer() ); - PrintValues ("Reverse" , myAL ); - // + public static void Main() + { + // + // Creates and initializes a new ArrayList. + ArrayList myAL = new ArrayList(); + myAL.Add("Eric"); + myAL.Add("Mark"); + myAL.Add("Lance"); + myAL.Add("Rob"); + myAL.Add("Kris"); + myAL.Add("Brad"); + myAL.Add("Kit"); + myAL.Add("Bradley"); + myAL.Add("Keith"); + myAL.Add("Susan"); - // - string [] names = (string[]) myAL.ToArray (typeof(string)); - // - } - // - public static void PrintValues(string title, IEnumerable myList ) { - Console.Write ("{0,10}: ", title); - StringBuilder sb = new StringBuilder(); - foreach (string s in myList) { - sb.AppendFormat( "{0}, ", s); - } - sb.Remove (sb.Length-2,2); - Console.WriteLine(sb); - } - // + // Displays the properties and values of the ArrayList. + Console.WriteLine("Count: {0}", myAL.Count); + // + + PrintValues("Unsorted", myAL); + // + myAL.Sort(); + PrintValues("Sorted", myAL); + // + // + myAL.Sort(new ReverseStringComparer()); + PrintValues("Reverse", myAL); + // + + // + string[] names = (string[])myAL.ToArray(typeof(string)); + // + } + // + public static void PrintValues(string title, IEnumerable myList) + { + Console.Write("{0,10}: ", title); + StringBuilder sb = new StringBuilder(); + foreach (string s in myList) + { + sb.AppendFormat("{0}, ", s); + } + sb.Remove(sb.Length - 2, 2); + Console.WriteLine(sb); + } + // } // -public class ReverseStringComparer : IComparer { - public int Compare (object x, object y) { - string s1 = x as string; - string s2 = y as string; - //negate the return value to get the reverse order - return - String.Compare (s1,s2); - } +public class ReverseStringComparer : IComparer +{ + public int Compare(object? x, object? y) + { + string? s1 = x as string; + string? s2 = y as string; + //negate the return value to get the reverse order + return -String.Compare(s1, s2); + } } // diff --git a/snippets/csharp/System/String/Compare/Example.csproj b/snippets/csharp/System/String/Compare/Example.csproj index bce43df3e32..5f7ec23133c 100644 --- a/snippets/csharp/System/String/Compare/Example.csproj +++ b/snippets/csharp/System/String/Compare/Example.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable 8.0 True Remarks diff --git a/snippets/csharp/System/String/Compare/string.comp4.cs b/snippets/csharp/System/String/Compare/string.comp4.cs index 773db10ad8d..27c263c562f 100644 --- a/snippets/csharp/System/String/Compare/string.comp4.cs +++ b/snippets/csharp/System/String/Compare/string.comp4.cs @@ -8,7 +8,7 @@ public static void Main() { String str1 = "change"; String str2 = "dollar"; - String relation = null; + String relation; relation = symbol(String.Compare(str1, str2, false, new CultureInfo("en-US"))); Console.WriteLine("For en-US: {0} {1} {2}", str1, relation, str2); diff --git a/snippets/csharp/System/String/Copy/Program.cs b/snippets/csharp/System/String/Copy/Program.cs index a0bfce82f59..bef6e971d17 100644 --- a/snippets/csharp/System/String/Copy/Program.cs +++ b/snippets/csharp/System/String/Copy/Program.cs @@ -58,7 +58,7 @@ private static void UseUnmanaged() var original = "This is a single sentence."; var len = original.Length; var ptr = Marshal.StringToHGlobalUni(original); - string result; + string? result; unsafe { char *ch = (char *) ptr.ToPointer(); diff --git a/snippets/csharp/System/String/Copy/copy.csproj b/snippets/csharp/System/String/Copy/copy.csproj index 40d86a27bcb..1b0bbaffede 100644 --- a/snippets/csharp/System/String/Copy/copy.csproj +++ b/snippets/csharp/System/String/Copy/copy.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable 8.0 True diff --git a/snippets/csharp/System/String/Split/String.Split.csproj b/snippets/csharp/System/String/Split/String.Split.csproj index a40f4020f57..4b3ba452f12 100644 --- a/snippets/csharp/System/String/Split/String.Split.csproj +++ b/snippets/csharp/System/String/Split/String.Split.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable Split diff --git a/snippets/csharp/System/String/Split/identify.cs b/snippets/csharp/System/String/Split/identify.cs index 2c0b59f0846..8db587954f1 100644 --- a/snippets/csharp/System/String/Split/identify.cs +++ b/snippets/csharp/System/String/Split/identify.cs @@ -11,7 +11,7 @@ private static void SplitWithCharAndInt() _ = phrase.Split(default(char[]), 3, StringSplitOptions.RemoveEmptyEntries); - _ = phrase.Split((char[])null, 3, StringSplitOptions.RemoveEmptyEntries); + _ = phrase.Split((char[]?)null, 3, StringSplitOptions.RemoveEmptyEntries); _ = phrase.Split(null as char[], 3, StringSplitOptions.RemoveEmptyEntries); // @@ -24,7 +24,7 @@ private static void SplitWithStringAndInt() _ = phrase.Split(default(string[]), 3, StringSplitOptions.RemoveEmptyEntries); - _ = phrase.Split((string[])null, 3, StringSplitOptions.RemoveEmptyEntries); + _ = phrase.Split((string[]?)null, 3, StringSplitOptions.RemoveEmptyEntries); _ = phrase.Split(null as string[], 3, StringSplitOptions.RemoveEmptyEntries); // @@ -37,7 +37,7 @@ private static void SplitWithChar() _ = phrase.Split(default(char[]), StringSplitOptions.RemoveEmptyEntries); - _ = phrase.Split((char[])null, StringSplitOptions.RemoveEmptyEntries); + _ = phrase.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); _ = phrase.Split(null as char[], StringSplitOptions.RemoveEmptyEntries); // @@ -50,7 +50,7 @@ private static void SplitWithString() _ = phrase.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries); - _ = phrase.Split((string[])null, StringSplitOptions.RemoveEmptyEntries); + _ = phrase.Split((string[]?)null, StringSplitOptions.RemoveEmptyEntries); _ = phrase.Split(null as string[], StringSplitOptions.RemoveEmptyEntries); // diff --git a/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Read Example/CS/SqlDataReader.Read.csproj b/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Read Example/CS/SqlDataReader.Read.csproj index 97be8759373..fb16c894d2e 100644 --- a/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Read Example/CS/SqlDataReader.Read.csproj +++ b/snippets/csharp/VS_Snippets_ADO.NET/Classic WebData SqlDataReader.Read Example/CS/SqlDataReader.Read.csproj @@ -3,6 +3,7 @@ Exe net6.0 + enable diff --git a/xml/System.IO/Path.xml b/xml/System.IO/Path.xml index aae3b18a5f0..4a04ce0733b 100644 --- a/xml/System.IO/Path.xml +++ b/xml/System.IO/Path.xml @@ -62,54 +62,54 @@ Performs operations on instances that contain file or directory path information. These operations are performed in a cross-platform manner. - . + . .NET Core 1.1 and later versions and .NET Framework 4.6.2 and later versions also support access to file system objects that are device names, such as "\\\\?\\C:\\". For more information on file path formats on Windows, see [File path formats on Windows systems](/dotnet/standard/io/file-path-formats). Most members of the `Path` class do not interact with the file system and do not verify the existence of the file specified by a path string. `Path` class members that modify a path string, such as , have no effect on names of files in the file system. - + Some `Path` members do validate the contents of a specified path string, and throw an if the string contains characters that are not valid in path strings, as defined in the characters returned from the method. For example, on Windows-based desktop platforms, invalid path characters might include quote ("), less than (\<), greater than (>), pipe (|), backspace (\\b), null (\\0), and Unicode characters 16 through 18 and 20 through 25. This validation behavior varies between .NET versions: - + - On .NET Framework and .NET Core versions older than 2.1: All `Path` members that take a path as an argument throw an if they detect invalid path characters. - + - On .NET Core 2.1 and later versions: is the only member that throws an if the string contains invalid path characters. - - The members of the `Path` class enable you to quickly and easily perform common operations such as determining whether a file name extension is part of a path, and combining two strings into one path name. - - All members of the `Path` class are static and can therefore be called without having an instance of a path. - + + The members of the `Path` class enable you to quickly and easily perform common operations such as determining whether a file name extension is part of a path, and combining two strings into one path name. + + All members of the `Path` class are static and can therefore be called without having an instance of a path. + > [!NOTE] -> In members that accept a path as an input string, that path must be well-formed or an exception is raised. For example, if a path is fully qualified but begins with a space, the path is not trimmed in methods of the class. Therefore, the path is malformed and an exception is raised. Similarly, a path or a combination of paths cannot be fully qualified twice. For example, "c:\\temp c:\\windows" also raises an exception in most cases. Ensure that your paths are well-formed when using methods that accept a path string. - - In members that accept a path, the path can refer to a file or just a directory. The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. For example, all the following are acceptable paths: - -- "c:\\\\MyDir\\\\MyFile.txt" in C#, or "c:\\MyDir\\MyFile.txt" in Visual Basic. - -- "c:\\\\MyDir" in C#, or "c:\\MyDir" in Visual Basic. - -- "MyDir\\\\MySubdir" in C#, or "MyDir\\MySubDir" in Visual Basic. - -- "\\\\\\\\MyServer\\\\MyShare" in C#, or "\\\\MyServer\\MyShare" in Visual Basic. - - Because all these operations are performed on strings, it is impossible to verify that the results are valid in all scenarios. For example, the method parses a string that you pass to it and returns the extension from that string. However, this does not mean that a file with that extension exists on the disk. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - -## Examples - The following example demonstrates some of the main members of the `Path` class. - +> In members that accept a path as an input string, that path must be well-formed or an exception is raised. For example, if a path is fully qualified but begins with a space, the path is not trimmed in methods of the class. Therefore, the path is malformed and an exception is raised. Similarly, a path or a combination of paths cannot be fully qualified twice. For example, "c:\\temp c:\\windows" also raises an exception in most cases. Ensure that your paths are well-formed when using methods that accept a path string. + + In members that accept a path, the path can refer to a file or just a directory. The specified path can also refer to a relative path or a Universal Naming Convention (UNC) path for a server and share name. For example, all the following are acceptable paths: + +- "c:\\\\MyDir\\\\MyFile.txt" in C#, or "c:\\MyDir\\MyFile.txt" in Visual Basic. + +- "c:\\\\MyDir" in C#, or "c:\\MyDir" in Visual Basic. + +- "MyDir\\\\MySubdir" in C#, or "MyDir\\MySubDir" in Visual Basic. + +- "\\\\\\\\MyServer\\\\MyShare" in C#, or "\\\\MyServer\\MyShare" in Visual Basic. + + Because all these operations are performed on strings, it is impossible to verify that the results are valid in all scenarios. For example, the method parses a string that you pass to it and returns the extension from that string. However, this does not mean that a file with that extension exists on the disk. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + +## Examples + The following example demonstrates some of the main members of the `Path` class. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/Path Class/CPP/path class.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Path/Overview/path class.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Path Class/VB/path class.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/Path Class/VB/path class.vb" id="Snippet1"::: + ]]> File and Stream I/O @@ -160,21 +160,21 @@ For more information on file path formats on Windows, see [File path formats on Provides a platform-specific alternate character used to separate directory levels in a path string that reflects a hierarchical file system organization. - . `AltDirectorySeparatorChar` and are both valid for separating directory levels in a path string. - -The value of this field is a slash ('/') on both Windows and Unix-based operating systems. - -## Examples + . `AltDirectorySeparatorChar` and are both valid for separating directory levels in a path string. + +The value of this field is a slash ('/') on both Windows and Unix-based operating systems. + +## Examples The following example displays field values on Windows and on Unix-based systems. Note that Windows supports either the forward slash (which is returned by the field) or the backslash (which is returned by the field) as path separator characters, while Unix-based systems support only the forward slash. :::code language="csharp" source="~/snippets/csharp/System.IO/Path/DirectorySeparatorChar/Program.cs"::: :::code language="vb" source="~/snippets/visualbasic/api/system.io/path/directoryseparatorchar/program.vb"::: - + ]]> File and Stream I/O @@ -230,36 +230,36 @@ The following example displays field values on Windows and The path information to modify. The new extension (with or without a leading period). Specify to remove an existing extension from . Changes the extension of a path string. - The modified path information. - + The modified path information. + On Windows-based desktop platforms, if is or an empty string (""), the path information is returned unmodified. If is , the returned string contains the specified path with its extension removed. If has no extension, and is not , the returned path string contains appended to the end of . - .NET Framework and .NET Core versions older than 2.1: contains one or more of the invalid characters defined in . @@ -280,9 +280,9 @@ The following example displays field values on Windows and Combines strings into a path. - or methods. @@ -345,29 +345,29 @@ This method is intended to concatenate individual strings into a single string t Combines an array of strings into a path. The combined paths. - or the character, the `Combine` method adds a character between that element and the next one. Note that, if the element ends in a path separator character that is not appropriate for the target platform, the `Combine` method preserves the original path separator character and appends a supported one. The following example compares the result on Windows and Unix-based systems when the backslash is used as a path separator character. :::code language="csharp" source="~/snippets/csharp/System.IO/Path/Combine/Program.cs" id="Snippet1"::: -:::code language="vb" source="~/snippets/visualbasic/api/system.io/path/combine/program.vb" id="Snippet1"::: - - Zero-length strings are omitted from the combined path. - - The parameters are not parsed if they have white space. - - .NET Framework and .NET Core versions older than 2.1: Not all invalid characters for directory and file names are interpreted as unacceptable by the `Combine` method, because you can use these characters for search wildcard characters. For example, while `Path.Combine("c:\\", "*.txt")` might be invalid if you were to create a file from it, it is valid as a search string. It is therefore successfully interpreted by the `Combine` method. - -## Examples - The following example combines an array of strings into a path. - +:::code language="vb" source="~/snippets/visualbasic/api/system.io/path/combine/program.vb" id="Snippet1"::: + + Zero-length strings are omitted from the combined path. + + The parameters are not parsed if they have white space. + + .NET Framework and .NET Core versions older than 2.1: Not all invalid characters for directory and file names are interpreted as unacceptable by the `Combine` method, because you can use these characters for search wildcard characters. For example, while `Path.Combine("c:\\", "*.txt")` might be invalid if you were to create a file from it, it is valid as a search string. It is therefore successfully interpreted by the `Combine` method. + +## Examples + The following example combines an array of strings into a path. + :::code language="csharp" source="~/snippets/csharp/System.IO/Path/Combine/program1.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.path.combine/vb/program.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.path.combine/vb/program.vb" id="Snippet3"::: + ]]> .NET Framework and .NET Core versions older than 2.1: One of the strings in the array contains one or more of the invalid characters defined in . @@ -423,31 +423,29 @@ If any element in `paths` but the last one is not a drive and does not end with Combines two strings into a path. The combined paths. If one of the specified paths is a zero-length string, this method returns the other path. If contains an absolute path, this method returns . - , , or , is appended to `path1` before concatenation. Note that if `path1` ends in a path separator character that is not appropriate for the target platform, the `Combine` method preserves the original path separator character and appends a supported one. The following example compares the result on Windows and Unix-based systems when the backslash is used as a path separator character. - + , , or , is appended to `path1` before concatenation. Note that if `path1` ends in a path separator character that is not appropriate for the target platform, the `Combine` method preserves the original path separator character and appends a supported one. The following example compares the result on Windows and Unix-based systems when the backslash is used as a path separator character. + :::code language="csharp" source="~/snippets/csharp/System.IO/Path/Combine/Program.cs" id="Snippet2"::: -:::code language="vb" source="~/snippets/visualbasic/api/system.io/path/combine/program.vb" id="Snippet2"::: - - If `path2` does not include a root (for example, if `path2` does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If `path2` includes a root, `path2` is returned. - - The parameters are not parsed if they have white space. Therefore, if `path2` includes white space (for example, " \\file.txt "), the method appends `path2` to `path1` instead of returning only `path2`. - - .NET Framework and .NET Core versions older than 2.1: Not all invalid characters for directory and file names are interpreted as unacceptable by the `Combine` method, because you can use these characters for search wildcard characters. For example, while `Path.Combine("c:\\", "*.txt")` might be invalid if you were to create a file from it, it is valid as a search string. It is therefore successfully interpreted by the `Combine` method. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example demonstrates using the `Combine` method on a Windows-based desktop platform. - +:::code language="vb" source="~/snippets/visualbasic/api/system.io/path/combine/program.vb" id="Snippet2"::: + + If `path2` does not include a root (for example, if `path2` does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If `path2` includes a root, `path2` is returned. + + The parameters are not parsed if they have white space. Therefore, if `path2` includes white space (for example, " \\file.txt "), the method appends `path2` to `path1` instead of returning only `path2`. + + .NET Framework and .NET Core versions older than 2.1: Not all invalid characters for directory and file names are interpreted as unacceptable by the `Combine` method, because you can use these characters for search wildcard characters. For example, while `Path.Combine("c:\\", "*.txt")` might be invalid if you were to create a file from it, it is valid as a search string. It is therefore successfully interpreted by the `Combine` method. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + +## Examples + The following example demonstrates using the `Combine` method on Windows. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/pathcombine/CPP/pathcombine.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Path/Combine/pathcombine.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/pathcombine/VB/pathcombine.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/pathcombine/VB/pathcombine.vb" id="Snippet1"::: + ]]> .NET Framework and .NET Core versions older than 2.1: or contains one or more of the invalid characters defined in . @@ -507,32 +505,32 @@ If any element in `paths` but the last one is not a drive and does not end with Combines three strings into a path. The combined paths. - , , or , is appended to `path1` or `path2` before concatenation. Note that if `path1` or `path2` ends in a path separator character that is not appropriate for the target platform, the `Combine` method preserves the original path separator character and appends a supported one. The following example compares the result on Windows and Unix-based systems when the backslash is used as a path separator character. + , , or , is appended to `path1` or `path2` before concatenation. Note that if `path1` or `path2` ends in a path separator character that is not appropriate for the target platform, the `Combine` method preserves the original path separator character and appends a supported one. The following example compares the result on Windows and Unix-based systems when the backslash is used as a path separator character. :::code language="csharp" source="~/snippets/csharp/System.IO/Path/Combine/Program.cs" id="Snippet3"::: -:::code language="vb" source="~/snippets/visualbasic/api/system.io/path/combine/program.vb" id="Snippet3"::: - - If `path2` does not include a root (for example, if `path2` does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If `path2` includes a root, `path2` is returned. - - The parameters are not parsed if they have white space. Therefore, if `path2` includes white space (for example, " \\file.txt "), the method appends `path2` to `path1`. - - .NET Framework and .NET Core versions older than 2.1: Not all invalid characters for directory and file names are interpreted as unacceptable by the `Combine` method, because you can use these characters for search wildcard characters. For example, while `Path.Combine("c:\\", "*.txt")` might be invalid if you were to create a file from it, it is valid as a search string. It is therefore successfully interpreted by the `Combine` method. - - - -## Examples - The following example combines three paths. - +:::code language="vb" source="~/snippets/visualbasic/api/system.io/path/combine/program.vb" id="Snippet3"::: + + If `path2` does not include a root (for example, if `path2` does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If `path2` includes a root, `path2` is returned. + + The parameters are not parsed if they have white space. Therefore, if `path2` includes white space (for example, " \\file.txt "), the method appends `path2` to `path1`. + + .NET Framework and .NET Core versions older than 2.1: Not all invalid characters for directory and file names are interpreted as unacceptable by the `Combine` method, because you can use these characters for search wildcard characters. For example, while `Path.Combine("c:\\", "*.txt")` might be invalid if you were to create a file from it, it is valid as a search string. It is therefore successfully interpreted by the `Combine` method. + + + +## Examples + The following example combines three paths. + :::code language="csharp" source="~/snippets/csharp/System.IO/Path/Combine/program1.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.path.combine/vb/program.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.path.combine/vb/program.vb" id="Snippet1"::: + ]]> .NET Framework and .NET Core versions older than 2.1: , , or contains one or more of the invalid characters defined in . @@ -589,32 +587,32 @@ If any element in `paths` but the last one is not a drive and does not end with Combines four strings into a path. The combined paths. - , , or , is appended to it before concatenation. Note that if `path1`, `path2`, or `path3` ends in a path separator character that is not appropriate for the target platform, the `Combine` method preserves the original path separator character and appends a supported one. The following example compares the result on Windows and Unix-based systems when the backslash is used as a path separator character. + , , or , is appended to it before concatenation. Note that if `path1`, `path2`, or `path3` ends in a path separator character that is not appropriate for the target platform, the `Combine` method preserves the original path separator character and appends a supported one. The following example compares the result on Windows and Unix-based systems when the backslash is used as a path separator character. :::code language="csharp" source="~/snippets/csharp/System.IO/Path/Combine/Program.cs" id="Snippet4"::: -:::code language="vb" source="~/snippets/visualbasic/api/system.io/path/combine/program.vb" id="Snippet4"::: - - If `path2` does not include a root (for example, if `path2` does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If `path2` includes a root, `path2` is returned. - - The parameters are not parsed if they have white space. Therefore, if `path2` includes white space (for example, " \\file.txt "), the method appends `path2` to `path1`. - - .NET Framework and .NET Core versions older than 2.1: Not all invalid characters for directory and file names are interpreted as unacceptable by the `Combine` method, because you can use these characters for search wildcard characters. For example, while `Path.Combine("c:\\", "*.txt")` might be invalid if you were to create a file from it, it is valid as a search string. It is therefore successfully interpreted by the `Combine` method. - - - -## Examples - The following example combines four paths. - +:::code language="vb" source="~/snippets/visualbasic/api/system.io/path/combine/program.vb" id="Snippet4"::: + + If `path2` does not include a root (for example, if `path2` does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If `path2` includes a root, `path2` is returned. + + The parameters are not parsed if they have white space. Therefore, if `path2` includes white space (for example, " \\file.txt "), the method appends `path2` to `path1`. + + .NET Framework and .NET Core versions older than 2.1: Not all invalid characters for directory and file names are interpreted as unacceptable by the `Combine` method, because you can use these characters for search wildcard characters. For example, while `Path.Combine("c:\\", "*.txt")` might be invalid if you were to create a file from it, it is valid as a search string. It is therefore successfully interpreted by the `Combine` method. + + + +## Examples + The following example combines four paths. + :::code language="csharp" source="~/snippets/csharp/System.IO/Path/Combine/program1.cs" id="Snippet2"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.path.combine/vb/program.vb" id="Snippet2"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.io.path.combine/vb/program.vb" id="Snippet2"::: + ]]> .NET Framework and .NET Core versions older than 2.1: , , , or contains one or more of the invalid characters defined in . @@ -664,17 +662,17 @@ If any element in `paths` but the last one is not a drive and does not end with Provides a platform-specific character used to separate directory levels in a path string that reflects a hierarchical file system organization. - and `DirectorySeparatorChar` are both valid for separating directory levels in a path string. - + and `DirectorySeparatorChar` are both valid for separating directory levels in a path string. + When you are using .NET Core to develop applications that run on multiple platforms: - If you prefer to hard-code the directory separator character, you should use the forward slash (`/`) character. It is the only recognized directory separator character on Unix systems, as the output from the example shows, and is the on Windows. -- Use string concatenation to dynamically retrieve the path separator character at runtime and incorporate it into file system paths. For example, +- Use string concatenation to dynamically retrieve the path separator character at runtime and incorporate it into file system paths. For example, ```csharp separator = Path.DirectorySeparatorChar; @@ -684,7 +682,7 @@ When you are using .NET Core to develop applications that run on multiple platfo ```vb separator = Path.DirectorySeparatorChar path = $"{separator}users{separator}user1{separator}" - ``` + ``` You can also retrieve the value from the property, since it is the same on both Windows and Unix-based systems. @@ -692,13 +690,13 @@ When you are using .NET Core to develop applications that run on multiple platfo If your application is not cross-platform, you can use the separator appropriate for your system. -## Examples +## Examples -The following example displays field values on Windows and on Unix-based systems. Note that Windows supports either the forward slash (which is returned by the field) or the backslash (which is returned by the field) as path separator characters, while Unix-based systems support only the forward slash. +The following example displays field values on Windows and on Unix-based systems. Note that Windows supports either the forward slash (which is returned by the field) or the backslash (which is returned by the field) as path separator characters, while Unix-based systems support only the forward slash. :::code language="csharp" source="~/snippets/csharp/System.IO/Path/DirectorySeparatorChar/Program.cs"::: :::code language="vb" source="~/snippets/visualbasic/api/system.io/path/directoryseparatorchar/program.vb"::: - + ]]> File and Stream I/O @@ -951,8 +949,8 @@ Unlike the string overload, this method doesn't normalize directory separators. Returns the directory information for the specified path. Directory information for , or if denotes a root directory or is null. Returns if does not contain directory information. - or . If the path consists of a root directory, such as "c:\\", `null` is returned. @@ -963,13 +961,13 @@ Because the returned path does not include the last directory separator characte For a list of common I/O tasks, see [Common I/O tasks](/dotnet/standard/io/common-i-o-tasks). -## Examples - The following example demonstrates using the `GetDirectoryName` method on a Windows-based desktop platform. - +## Examples + The following example demonstrates using the `GetDirectoryName` method on a Windows-based desktop platform. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.Path Members/CPP/pathmembers.cpp" id="Snippet3"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Path/ChangeExtension/pathmembers.cs" id="Snippet3"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet3"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet3"::: + ]]> .NET Framework and .NET Core versions older than 2.1: The parameter contains invalid characters, is empty, or contains only white spaces. @@ -1021,9 +1019,9 @@ Note: In if does not have extension information. - or character, the returned read-only span contains the period and the characters after it; otherwise, is returned. +This method obtains the extension of `path` by searching `path` for a period ("."), starting from the last character in the read-only span and continuing toward its first character. If a period is found before a or character, the returned read-only span contains the period and the characters after it; otherwise, is returned. ]]> @@ -1078,21 +1076,21 @@ This method obtains the extension of `path` by searching `path` for a period (". Returns the extension (including the period ".") of the specified path string. The extension of the specified path (including the period "."), or , or . If is , returns . If does not have extension information, returns . - or character, the returned string contains the period and the characters after it; otherwise, is returned. -This method obtains the extension of `path` by searching `path` for a period (.), starting with the last character in `path` and continuing toward the first character. If a period is found before a or character, the returned string contains the period and the characters after it; otherwise, is returned. - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - -## Examples - The following example demonstrates using the `GetExtension` method on a Windows-based desktop platform. - + +## Examples + The following example demonstrates using the `GetExtension` method on a Windows-based desktop platform. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.Path Members/CPP/pathmembers.cpp" id="Snippet4"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Path/ChangeExtension/pathmembers.cs" id="Snippet4"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet4"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet4"::: + ]]> .NET Framework and .NET Core versions older than 2.1: contains one or more of the invalid characters defined in . @@ -1140,7 +1138,7 @@ This method obtains the extension of `path` by searching `path` for a period (.) Returns the file name and extension of a file path that is represented by a read-only character span. The characters after the last directory separator character in . - . If `path` contains no separator character, the method returns `path`. @@ -1197,27 +1195,27 @@ The returned read-only span contains the characters of the path that follow the Returns the file name and extension of the specified path string. The characters after the last directory separator character in . If the last character of is a directory or volume separator character, this method returns . If is , this method returns . - and . +The returned value is `null` if the file path is `null`. + +The separator characters used to determine the start of the file name are and . Because *\\* is a legal file name on Unix, `GetFileName` running under Unix-based platforms cannot correctly return the file name from a Windows-based path like *C:\\mydir\\myfile.ext*, but `GetFileName` running under Windows-based platforms can correctly return the file name from a Unix-based path like */tmp/myfile.ext*, so the behavior of the `GetFileName` method is not strictly the same on Unix-based and Windows-based platforms. -For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example demonstrates the behavior of the `GetFileName` method on a Windows-based desktop platform. - +For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example demonstrates the behavior of the `GetFileName` method on a Windows-based desktop platform. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.Path Members/CPP/pathmembers.cpp" id="Snippet5"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Path/ChangeExtension/pathmembers.cs" id="Snippet5"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet5"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet5"::: + ]]> .NET Framework and .NET Core versions older than 2.1: contains one or more of the invalid characters defined in . @@ -1316,22 +1314,22 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo Returns the file name of the specified path string without the extension. The string returned by , minus the last period (.) and all characters following it. - .NET Framework and .NET Core versions older than 2.1: contains one or more of the invalid characters defined in . @@ -1393,36 +1391,36 @@ For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/commo Returns the absolute path for the specified path string. The fully qualified location of , such as "C:\\MyFile.txt". - [!IMPORTANT] > If `path` is a relative path, this overload returns a fully qualified path that can be based on the current drive and current directory. The current drive and current directory can change at any time as an application executes. As a result, the path returned by this overload cannot be determined in advance. To return a deterministic path, call the overload. You can also call the method to determine whether a path is fully qualified or relative and therefore whether a call to `GetFullPath` is necessary. - However, if `path` does exist, the caller must have permission to obtain path information for `path`. Note that unlike most members of the class, this method accesses the file system. - - This method uses the current directory and current volume information to fully qualify `path`. If you specify a file name only in `path`, `GetFullPath` returns the fully qualified path of the current directory. - - If you pass in a short file name, it is expanded to a long file name. - - If a path contains no significant characters, it is invalid unless it contains one or more "." characters followed by any number of spaces; then it will be parsed as either "." or "..". + However, if `path` does exist, the caller must have permission to obtain path information for `path`. Note that unlike most members of the class, this method accesses the file system. + + This method uses the current directory and current volume information to fully qualify `path`. If you specify a file name only in `path`, `GetFullPath` returns the fully qualified path of the current directory. + + If you pass in a short file name, it is expanded to a long file name. + + If a path contains no significant characters, it is invalid unless it contains one or more "." characters followed by any number of spaces; then it will be parsed as either "." or "..". .NET Core 1.1 and later versions and .NET Framework 4.6.2 and later versions also support paths that include device names, such as "\\\\?\\C:\\". For more information on file path formats on Windows, see [File path formats on Windows systems](/dotnet/standard/io/file-path-formats). For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - -## Examples - The following example demonstrates the `GetFullPath` method on a Windows-based desktop platform. - + +## Examples + The following example demonstrates the `GetFullPath` method on a Windows-based desktop platform. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.Path Members/CPP/pathmembers.cpp" id="Snippet7"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Path/ChangeExtension/pathmembers.cs" id="Snippet7"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet7"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet7"::: + ]]> @@ -1483,20 +1481,20 @@ For more information on file path formats on Windows, see [File path formats on Returns an absolute path from a relative path and a fully qualified base path. The absolute path. - method and returns the result. -Use this method to return a deterministic path based on a specified volume and rooted directory when you're using relative paths. Using a predefined `basePath` rather than one based on the current drive directory guards against unwanted file paths caused by unexpected changes in the current drive and directory. +Use this method to return a deterministic path based on a specified volume and rooted directory when you're using relative paths. Using a predefined `basePath` rather than one based on the current drive directory guards against unwanted file paths caused by unexpected changes in the current drive and directory. ## Examples The following example defines a variable, `basePath`, to represent an application's current directory. It then passes it to the `GetFullPath` method to get a fully qualified path to the application's data directory. -:::code language="csharp" source="~/snippets/csharp/System.IO/Path/GetFullPath/Program.cs"::: -:::code language="vb" source="~/snippets/visualbasic/api/system.io/path/getfullpath/program.vb"::: +:::code language="csharp" source="~/snippets/csharp/System.IO/Path/GetFullPath/Program.cs"::: +:::code language="vb" source="~/snippets/visualbasic/api/system.io/path/getfullpath/program.vb"::: ]]> @@ -1553,20 +1551,20 @@ The following example defines a variable, `basePath`, to represent an applicatio Gets an array containing the characters that are not allowed in file names. An array containing the characters that are not allowed in file names. - ), pipe (|), backspace (\\b), null (\\0) and tab (\\t). - - - -## Examples - The following example demonstrates the method and the method to retrieve invalid characters. - + + + +## Examples + The following example demonstrates the method and the method to retrieve invalid characters. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/IO.Path.GetInvalidFile-PathChars/cpp/example.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Path/GetInvalidFileNameChars/example.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IO.Path.GetInvalidFile-PathChars/VB/example.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IO.Path.GetInvalidFile-PathChars/VB/example.vb" id="Snippet1"::: + ]]> @@ -1614,18 +1612,18 @@ The following example defines a variable, `basePath`, to represent an applicatio Gets an array containing the characters that are not allowed in path names. An array containing the characters that are not allowed in path names. - method and the method to retrieve invalid characters. - +## Examples + The following example demonstrates the method and the method to retrieve invalid characters. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR/IO.Path.GetInvalidFile-PathChars/cpp/example.cpp" id="Snippet1"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Path/GetInvalidFileNameChars/example.cs" id="Snippet1"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IO.Path.GetInvalidFile-PathChars/VB/example.vb" id="Snippet1"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR/IO.Path.GetInvalidFile-PathChars/VB/example.vb" id="Snippet1"::: + ]]> @@ -1696,7 +1694,7 @@ Possible patterns for the read-only character span returned by this method are a - "\\\\ComputerName\\SharedFolder" (Windows: a UNC path). - "\\\\?\\C:" (Windows: a DOS device path, supported in .NET Core 1.1 and later versions, and in .NET Framework 4.6.2 and later versions). - + For more information on file paths on Windows, see [File path formats on Windows systems](/dotnet/standard/io/file-path-formats). For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). @@ -1760,11 +1758,11 @@ For more information on file paths on Windows, see [File path formats on Windows The root directory of if it is rooted. -or- - + if does not contain root directory information. -or- - + if is or is effectively empty. Returns a random folder name or file name. A random folder name or file name. - , does not create a file. - - -## Examples - The following example show output from the method. - + + +## Examples + The following example show output from the method. + :::code language="csharp" source="~/snippets/csharp/System.IO/Path/ChangeExtension/pathmembers20.cs" id="Snippet20"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers20.vb" id="Snippet20"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers20.vb" id="Snippet20"::: + ]]> @@ -1919,9 +1917,9 @@ Unlike , Returns a relative path from one path to another. The relative path, or if the paths don't share the same root. - method before calculating the difference. The method uses the default file path comparison for the current platform ( for Windows and MacOs, for Linux. +Paths are resolved by calling the method before calculating the difference. The method uses the default file path comparison for the current platform ( for Windows and MacOs, for Linux. ]]> @@ -1981,24 +1979,24 @@ Paths are resolved by calling the method be Creates a uniquely named, zero-byte temporary file on disk and returns the full path of that file. The full path of the temporary file. - method. -This method creates a temporary file with a *.tmp* file extension and returns the path to it. The temporary file is created within the user's temporary folder, which is the path returned by the method. - On .NET 7 and earlier versions, when using this method on Windows, the method raises an if it's used to create more than 65535 files without deleting previous temporary files. This limitation does not exist on operating systems other than Windows. Starting in .NET 8, the limitation does not exist on *any* operating system. - - The method will raise an if no unique temporary file name is available. To resolve this error, delete all unneeded temporary files. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - + + The method will raise an if no unique temporary file name is available. To resolve this error, delete all unneeded temporary files. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + ]]> - An I/O error occurs, such as no unique temporary file name is available. - + An I/O error occurs, such as no unique temporary file name is available. + -or- - + This method was unable to create a temporary file. File and Stream I/O How to: Read Text from a File @@ -2054,22 +2052,22 @@ On .NET 7 and earlier versions, when using this method on Windows, the Returns the path of the current user's temporary folder. The path to the temporary folder, ending with a . - method. - -```vb -Dim result As String = Path.GetTempPath() -Console.WriteLine(result) -``` - -```csharp -string result = Path.GetTempPath(); -Console.WriteLine(result); -``` - - This example produces output similar to the following. - -``` -C:\Users\UserName\AppData\Local\Temp\ -``` - +## Examples + The following code shows how to call the method. + +```vb +Dim result As String = Path.GetTempPath() +Console.WriteLine(result) +``` + +```csharp +string result = Path.GetTempPath(); +Console.WriteLine(result); +``` + + This example produces output similar to the following. + +``` +C:\Users\UserName\AppData\Local\Temp\ +``` + ]]> The caller does not have the required permissions. @@ -2148,7 +2146,7 @@ C:\Users\UserName\AppData\Local\Temp\ if the characters that follow the last directory separator character or volume separator in the path include a period (".") followed by one or more characters; otherwise, . - if the characters that follow the last directory separator (\\ or /) or volume separator (:) in the path include a period (.) followed by one or more characters; otherwise, . - , , or character is encountered, this method returns `true`. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - - - -## Examples - The following example demonstrates the use of the `HasExtension` method. - + , , or character is encountered, this method returns `true`. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + + + +## Examples + The following example demonstrates the use of the `HasExtension` method. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.Path Members/CPP/pathmembers.cpp" id="Snippet11"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Path/ChangeExtension/pathmembers.cs" id="Snippet11"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet11"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet11"::: + ]]> .NET Framework and .NET Core versions older than 2.1: contains one or more of the invalid characters defined in . @@ -2291,22 +2289,22 @@ A trailing period in `path` is not considered an extension. Provides a platform-specific array of characters that cannot be specified in path string arguments passed to members of the class. - remarks to learn what the set of characters returned by this field is. - + > [!CAUTION] -> Do not use if you think your code might execute in the same application domain as untrusted code. is an array, so its elements can be overwritten. If untrusted code overwrites elements of , it might cause your code to malfunction in ways that could be exploited. +> Do not use if you think your code might execute in the same application domain as untrusted code. is an array, so its elements can be overwritten. If untrusted code overwrites elements of , it might cause your code to malfunction in ways that could be exploited. + +## Examples + The following example demonstrates the use of the `InvalidPathChars` property. -## Examples - The following example demonstrates the use of the `InvalidPathChars` property. - :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.Path Members/CPP/pathmembers.cpp" id="Snippet13"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Path/ChangeExtension/pathmembers.cs" id="Snippet13"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet13"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet13"::: + ]]> File and Stream I/O @@ -2318,11 +2316,11 @@ The array returned from this method is not guaranteed to contain the complete se Returns a value that indicates whether a file path is fully qualified. - and the characters. It does not perform any validation on the path that is passed to it as an argument. As a result, URIs are interpreted as relative paths and return `false`. +## Remarks + +The overloads of the `IsPathFullyQualified` method handle paths that use both the and the characters. It does not perform any validation on the path that is passed to it as an argument. As a result, URIs are interpreted as relative paths and return `false`. There is a difference between a fully qualified path (as indicated by the `IsPathFullyQualified` method) and a rooted path (as indicated by the method). A *fully qualified path* or *absolute path* always defines an exact path from a particular drive or device to a target file or directory, and does not depend on the current drive or current directory. For example, on Windows systems, *C:/users/user1/documents/reports/2019/january/highlights.pdf* defines an absolute path from the root of the C: drive to the target file, *highlights.pdf*. A *rooted path* specifies either a starting drive or root directory, but depends on either the current directory (if it is rooted by a specified drive) or the current drive (if it is rooted by the root directory). The following example illustrates the difference between fully qualified paths and rooted paths. @@ -2372,7 +2370,7 @@ There is a difference between a fully qualified path (as indicated by the `IsPat if the path is fixed to a specific drive or UNC path; if the path is relative to the current drive or working directory. - @@ -2436,11 +2434,11 @@ This method handles paths that use the alternate directory separator. It's a fre Returns a value that indicates whether a file path contains a root. - if contains a root; otherwise, . - method returns `true` if the first character is a directory separator character such as "\\", or if the path starts with a drive letter and colon (:). For example, it returns `true` for `path` strings such as "\\\\MyDir\\MyFile.txt", "C:\\MyDir", or "C:MyDir". It returns `false` for `path` strings such as "MyDir". - - This method does not verify that the path or file name exists. - - For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). - -## Examples - The following example demonstrates how the `IsPathRooted` method can be used to test three strings. - + method returns `true` if the first character is a directory separator character such as "\\", or if the path starts with a drive letter and colon (:). For example, it returns `true` for `path` strings such as "\\\\MyDir\\MyFile.txt", "C:\\MyDir", or "C:MyDir". It returns `false` for `path` strings such as "MyDir". + + This method does not verify that the path or file name exists. + + For a list of common I/O tasks, see [Common I/O Tasks](/dotnet/standard/io/common-i-o-tasks). + +## Examples + The following example demonstrates how the `IsPathRooted` method can be used to test three strings. + :::code language="cpp" source="~/snippets/cpp/VS_Snippets_CLR_System/system.IO.Path Members/CPP/pathmembers.cpp" id="Snippet12"::: :::code language="csharp" source="~/snippets/csharp/System.IO/Path/ChangeExtension/pathmembers.cs" id="Snippet12"::: - :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet12"::: - + :::code language="vb" source="~/snippets/visualbasic/VS_Snippets_CLR_System/system.IO.Path Members/VB/pathmembers.vb" id="Snippet12"::: + ]]> .NET Framework and .NET Core versions older than 2.1: contains one or more of the invalid characters defined in . @@ -2678,25 +2676,25 @@ Not all invalid characters for directory and file names are interpreted as unacc Concatenates two path components into a single path. The combined paths. - of either `path1` or `path2` is zero, the method returns the other path. If the of both `path1` and `path2` is zero, the method returns . + of either `path1` or `path2` is zero, the method returns the other path. If the of both `path1` and `path2` is zero, the method returns . If `path1` ends in a path separator character that is not appropriate for the target platform, the `Join` method preserves the original path separator character and appends the supported one. This issue arises in hard-coded paths that use the Windows backslash ("\\") character, which is not recognized as a path separator on Unix-based systems. To work around this issue, you can: - Retrieve the value of the property rather than hard-coding a directory separator character. -- Use a forward slash ("/") as the directory separator character. This character is returned by the property on Unix-based systems and by the property on Windows systems. +- Use a forward slash ("/") as the directory separator character. This character is returned by the property on Unix-based systems and by the property on Windows systems. -Unlike the method, the method does not attempt to root the returned path. (That is, if `path2` is an absolute path, the `Join` method does not discard `path1` and return `path2` as the method does.) The following example illustrates the difference in the paths returned by the two methods. If the source of `path2` is user input, the method makes it possible for a user to access a file system resource (such as *C:/Users/User1/Documents/Financial/* in the case of the example) that the application did not intend to make accessible. +Unlike the method, the method does not attempt to root the returned path. (That is, if `path2` is an absolute path, the `Join` method does not discard `path1` and return `path2` as the method does.) The following example illustrates the difference in the paths returned by the two methods. If the source of `path2` is user input, the method makes it possible for a user to access a file system resource (such as *C:/Users/User1/Documents/Financial/* in the case of the example) that the application did not intend to make accessible. -Not all invalid characters for directory and file names are interpreted as unacceptable by the `Join` method, because you can use these characters for search wildcard characters. For example, while `Path.Join("c:\\", "*.txt")` might be invalid when creating a file, it is valid as a search string. The `Join` method therefore successfully interprets it. +Not all invalid characters for directory and file names are interpreted as unacceptable by the `Join` method, because you can use these characters for search wildcard characters. For example, while `Path.Join("c:\\", "*.txt")` might be invalid when creating a file, it is valid as a search string. The `Join` method therefore successfully interprets it. ## Examples -The following example illustrates the difference in the paths returned by the and methods. When the first string is an fully qualified path that includes a drive and root directory and the second is a relative path from the first path, the two methods produce identical results. In the second and third calls to the `ShowPathInformation` method, the strings returned by the two methods diverge. In the second method call, the first string argument is a drive, while the second is a rooted directory. The `Join` method concatenates the two strings and preserves duplicate path separators. The `Combine` method abandons the drive and returns a rooted directory on the current drive. If the application's current drive is C:\\ and the string is used to access a file or files in the directory, it would access C: instead of D:. Finally, because both arguments in the third call to `ShowPathInformation` are rooted, the `Join` method simply appends them to create a nonsensical file path, while the `Combine` method discards the first string and returns the second. Using this string for file access could give the application unintended access to sensitive files. +The following example illustrates the difference in the paths returned by the and methods. When the first string is an fully qualified path that includes a drive and root directory and the second is a relative path from the first path, the two methods produce identical results. In the second and third calls to the `ShowPathInformation` method, the strings returned by the two methods diverge. In the second method call, the first string argument is a drive, while the second is a rooted directory. The `Join` method concatenates the two strings and preserves duplicate path separators. The `Combine` method abandons the drive and returns a rooted directory on the current drive. If the application's current drive is C:\\ and the string is used to access a file or files in the directory, it would access C: instead of D:. Finally, because both arguments in the third call to `ShowPathInformation` are rooted, the `Join` method simply appends them to create a nonsensical file path, while the `Combine` method discards the first string and returns the second. Using this string for file access could give the application unintended access to sensitive files. :::code language="csharp" source="~/snippets/csharp/System.IO/Path/Combine/Program2.cs"::: :::code language="vb" source="~/snippets/visualbasic/api/system.io/path/combine2/program.vb"::: @@ -2808,10 +2806,10 @@ Not all invalid characters for directory and file names are interpreted as unacc Concatenates three path components into a single path. The concatenated path. - of any of `path1`, `path2`, or `path3` arguments is zero, the method concatenates the remaining arguments. If the of all components is zero, the method returns . If `path1` or `path2` ends in a path separator character that is not appropriate for the target platform, the `Join` method preserves the original path separator character and appends the supported one. This issue arises in hard-coded paths that use the Windows backslash ("\\") character, which is not recognized as a path separator on Unix-based systems. To work around this issue, you can: @@ -2821,7 +2819,7 @@ If `path1` or `path2` ends in a path separator character that is not appropriate - Use a forward slash ("/") as the directory separator character. This character is returned by the property on Unix-based systems and by the property on Windows systems. Unlike the method, the method does not attempt to root the returned path. (That is, if `path2` or `path3` is an absolute path, the `Join` method does not discard the previous paths as the method does.) - + Not all invalid characters for directory and file names are interpreted as unacceptable by the `Join` method, because you can use these characters for search wildcard characters. For example, while `Path.Join("c:\\", "temp", "*.txt")` might be invalid when creating a file, it is valid as a search string. The `Join` method therefore successfully interprets it. ## Examples @@ -3064,20 +3062,20 @@ Not all invalid characters for directory and file names are interpreted as unacc A platform-specific separator character used to separate path strings in environment variables. - File and Stream I/O @@ -3167,9 +3165,9 @@ Not all invalid characters for directory and file names are interpreted as unacc Attempts to concatenate individual path components to a preallocated character span, and returns a value that indicates whether the operation succeeded. - method, as the following example illustrates. @@ -3224,7 +3222,7 @@ The destination character span must be large enough to hold the concatenated pat if the concatenation operation is successful; otherwise, . - if the concatenation operation is successful; otherwise, . - Provides a platform-specific volume separator character. - File and Stream I/O diff --git a/xml/System/DateTime.xml b/xml/System/DateTime.xml index bdf926a0fe9..f2f6b2efbde 100644 --- a/xml/System/DateTime.xml +++ b/xml/System/DateTime.xml @@ -167,10 +167,8 @@ This article includes several examples that use the `DateTime` type: - [Persisting date and time values as strings in a culture and time invariant format](#persistence-02) - [Persisting date and time values as integers](#persistence-03) - [Persisting date and time values using the `XmlSerializer`](#persistence-04) -- [Persisting date and time values using the `BinaryFormatter`](#persistence-05) -- [Persisting date and time values with time zone data](#persistence-06) -## Quick links to Remarks topics. +## Quick links to Remarks topics This section contains topics for many common uses of the `DateTime` struct: @@ -196,7 +194,7 @@ Time values are measured in 100-nanosecond units called ticks. A particular date You can view the source for the entire set of examples from this article in either [Visual Basic](https://github.com/dotnet/dotnet-api-docs/tree/main/snippets/visualbasic/System.DateTime/), [F#](https://github.com/dotnet/dotnet-api-docs/tree/main/snippets/fsharp/System.DateTime/), or [C#](https://github.com/dotnet/dotnet-api-docs/tree/main/snippets/csharp/System.DateTime/) from the docs repository on GitHub. > [!NOTE] -> An alternative to the structure for working with date and time values in particular time zones is the structure. The structure stores date and time information in a private field and the number of minutes by which that date and time differs from UTC in a private field. This makes it possible for a value to reflect the time in a particular time zone, whereas a value can unambiguously reflect only UTC and the local time zone's time. For a discussion about when to use the structure or the structure when working with date and time values, see [Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo](/dotnet/standard/datetime/choosing-between-datetime). +> An alternative to the structure for working with date and time values in particular time zones is the structure. The structure stores date and time information in a private field and the number of minutes by which that date and time differs from UTC in a private field. This makes it possible for a value to reflect the time in a particular time zone, whereas a value can unambiguously reflect only UTC and the local time zone's time. For a discussion about when to use the structure or the structure when working with date and time values, see [Choosing Between DateTime, DateTimeOffset, TimeSpan, and TimeZoneInfo](/dotnet/standard/datetime/choosing-between-datetime). ### Initializing a DateTime object @@ -207,7 +205,7 @@ You can assign an initial value to a new `DateTime` value in many different ways - Parsing a `DateTime` value from its string representation. - Using Visual Basic-specific language features to instantiate a `DateTime`. -The following code snippets show examples of each: +The following code snippets show examples of each. #### Invoke Constructors @@ -429,12 +427,11 @@ For more information on dates and calendars, see [Working with Calendars](/dotne ### Persisting DateTime values -You can persist values in four ways: +You can persist values in the following ways: -- You [convert them to strings](#persisting-values-as-strings) and persist the strings. -- You [convert them to 64-bit integer values](#persisting-values-as-integers) (the value of the property) and persist the integers. -- You [serialize the DateTime values](#serializing-datetime-values). -- You [serialize the DateTime values along with time zone information](#serializing-datetime-and-time-zone-data). +- [Convert them to strings](#persisting-values-as-strings) and persist the strings. +- [Convert them to 64-bit integer values](#persisting-values-as-integers) (the value of the property) and persist the integers. +- [Serialize the DateTime values](#serializing-datetime-values). You must ensure that the routine that restores the values doesn't lose data or throw an exception regardless of which technique you choose. values should round-trip. That is, the original value and the restored value should be the same. And if the original value represents a single instant of time, it should identify the same moment of time when it's restored. @@ -444,7 +441,7 @@ To successfully restore values that are persisted as stri - Make the same assumptions about culture-specific formatting when you restore the string as when you persisted it. To ensure that a string can be restored on a system whose current culture is different from the culture of the system it was saved on, call the overload to save the string by using the conventions of the invariant culture. Call the or overload to restore the string by using the conventions of the invariant culture. Never use the , , or overloads, which use the conventions of the current culture. -- If the date represents a single moment of time, ensure that it represents the same moment in time when it's restored, even on a different time zone. Convert the value to Coordinated Universal Time (UTC) before saving it. You can also serialize the value along with time zone information. For more information about this approach, see [Serializing DateTime and time zone data](#serializing-datetime-and-time-zone-data). +- If the date represents a single moment of time, ensure that it represents the same moment in time when it's restored, even on a different time zone. Convert the value to Coordinated Universal Time (UTC) before saving it or use . The most common error made when persisting values as strings is to rely on the formatting conventions of the default or current culture. Problems arise if the current culture is different when saving and restoring the strings. The following example illustrates these problems. It saves five dates using the formatting conventions of the current culture, which in this case is English (United States). It restores the dates using the formatting conventions of a different culture, which in this case is English (United Kingdom). Because the formatting conventions of the two cultures are different, two of the dates can't be restored, and the remaining three dates are interpreted incorrectly. Also, if the original date and time values represent single moments in time, the restored times are incorrect because time zone information is lost. @@ -503,37 +500,7 @@ The following example uses the cla :::code language="fsharp" source="~/snippets/fsharp/System.DateTime/Persistence.fs" id="Snippet4"::: :::code language="vb" source="~/snippets/visualbasic/System.DateTime/Persistence.vb" id="Snippet4"::: -The previous example doesn't include time information. If a value represents a moment in time and is expressed as a local time, convert it from local time to UTC before serializing it by calling the method. After you deserialize it, convert it from UTC to local time by calling the method. The following example uses the class to serialize data on a system in the U.S. Pacific Standard Time zone and to deserialize it on a system in the U.S. Central Standard zone. - - -:::code language="csharp" source="~/snippets/csharp/System.DateTime/Persistence.cs" id="Snippet5"::: -:::code language="fsharp" source="~/snippets/fsharp/System.DateTime/Persistence.fs" id="Snippet5"::: -:::code language="vb" source="~/snippets/visualbasic/System.DateTime/Persistence.vb" id="Snippet5"::: - - -#### Serializing DateTime and time zone data - -The previous examples all assumed that values are expressed as local times. The code converted the values between UTC and local time so they reflect the same moment in time on the source and target systems. values may also reflect moments in time in a time zone other than local and UTC. Because the structure is not time zone-aware, you have to serialize both the value and the object that represents its time zone. Create a type whose fields include both the value and its time zone. The following example defines a `DateWithTimeZone` structure. - - -:::code language="csharp" source="~/snippets/csharp/System.DateTime/DateWithTimeZone.cs" id="Snippet6"::: -:::code language="fsharp" source="~/snippets/fsharp/System.DateTime/DateWithTimeZone.fs" id="Snippet6"::: -:::code language="vb" source="~/snippets/visualbasic/System.DateTime/DateWithTimeZone.vb" id="Snippet6"::: - -> [!IMPORTANT] -> The `DateWithTimeZone` structure is used in the next two examples, which serialize and deserialize an array of `DateWithTimeZone` objects. You can view the source for the entire set of examples from this article in either [Visual Basic](https://github.com/dotnet/dotnet-api-docs/tree/main/snippets/visualbasic/System.DateTime/), [F#](https://github.com/dotnet/dotnet-api-docs/tree/main/snippets/fsharp/System.DateTime/), or [C#](https://github.com/dotnet/dotnet-api-docs/tree/main/snippets/csharp/System.DateTime/) from the docs repository on GitHub. - -By using the `DateWithTimeZone` structure, you can then persist date and time along with time zone information. The following example uses the class to serialize an array of `DateWithTimeZone` objects. - -:::code language="csharp" source="~/snippets/csharp/System.DateTime/Persistence.cs" id="Snippet7"::: -:::code language="fsharp" source="~/snippets/fsharp/System.DateTime/Persistence.fs" id="Snippet7"::: -:::code language="vb" source="~/snippets/visualbasic/System.DateTime/Persistence.vb" id="Snippet7"::: - -The following example then calls the method to deserialize it. - -:::code language="csharp" source="~/snippets/csharp/System.DateTime/Persistence.cs" id="Snippet8"::: -:::code language="fsharp" source="~/snippets/fsharp/System.DateTime/Persistence.fs" id="Snippet8"::: -:::code language="vb" source="~/snippets/visualbasic/System.DateTime/Persistence.vb" id="Snippet8"::: +The previous example doesn't include time information. If a value represents a moment in time and is expressed as a local time, convert it from local time to UTC before serializing it by calling the method. After you deserialize it, convert it from UTC to local time by calling the method. ### DateTime vs. TimeSpan @@ -1579,9 +1546,9 @@ The behavior of the .NET Framework and COM means that if your application round- This constructor interprets `year`, `month` and `day` as a year, month and day in the Gregorian calendar. To instantiate a value by using the year, month and day in another calendar, call the constructor. - + The property is initialized to . - + For applications in which portability of date and time data or a limited degree of time zone awareness is important, you can use the corresponding constructor. @@ -1774,7 +1741,7 @@ For applications in which portability of date and time data or a limited degree This constructor interprets `year`, `month` and `day` as a year, month and day in the Gregorian calendar. To instantiate a value by using the year, month and day in another calendar, call the constructor. - + For applications in which portability of date and time data or a limited degree of time zone awareness is important, you can use the corresponding constructor. @@ -1863,7 +1830,7 @@ For applications in which portability of date and time data or a limited degree The allowable values for `year`, `month`, and `day` parameters depend on the `calendar` parameter. An exception is thrown if the specified date and time cannot be expressed using `calendar`. - + For applications in which portability of date and time data or a limited degree of time zone awareness is important, you can use the corresponding constructor. @@ -1954,7 +1921,7 @@ For applications in which portability of date and time data or a limited degree The allowable values for `year`, `month`, and `day` parameters depend on the `calendar` parameter. An exception is thrown if the specified date and time cannot be expressed using `calendar`. - + For applications in which portability of date and time data or a limited degree of time zone awareness is important, you can use the corresponding constructor. @@ -2250,10 +2217,10 @@ For applications in which portability of date and time data or a limited degree This method does not change the value of this . Instead, it returns a new whose value is the result of this operation. - + The fractional part of value is the fractional part of a microsecond. For example, 4.5 is equivalent to 4 microseconds and 50 ticks, where one microsecond = 10 ticks. - + The value parameter is rounded to the nearest integer. ]]>