C# – Visual Basic Bilingual Dictionary (2015)
Chapter 3
My Namespace to C#
The Visual Basic My namespace entries in this chapter appear alphabetically according to each member name within the hierarchy. For example, to discover the C# equivalent to the My.Computer.Network.IsAvailable property, locate the “IsAvailable Property” entry.
Some of the C# code samples in this chapter provide reasonable, but not exact, equivalents for My namespace members. For example, some members return a read-only collection of results, but the provided C# code might return an array or a generic collection instead.
Some My namespace members perform validation on data supplied to those members. In many cases, the provided C# code simplifies or eliminates such validation, providing just a basic translation for the My namespace member.
The full source code for the My namespace, written in Visual Basic, is available online. Visit http://referencesource.microsoft.com to access the code.
AllUsersApplicationData Property
♦ My.Computer.FileSystem.SpecialDirectories.AllUsersApplicationData
Returns the path to the “application data” folder shared by all local users.
VISUAL BASIC
Dim result As String = My.Computer.FileSystem.
SpecialDirectories.AllUsersApplicationData
C#
string result = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.
CommonApplicationData);
AltKeyDown Property
♦ My.Computer.Keyboard.AltKeyDown
Indicates whether an Alt key is currently pressed.
VISUAL BASIC
Dim result As Boolean = My.Computer.Keyboard.AltKeyDown
C#
// ----- For Windows Forms code:
bool result = ((System.Windows.Forms.Control.ModifierKeys &
System.Windows.Forms.Keys.Alt) != 0);
// ----- For XAML-centric code:
bool result = ((System.Windows.Input.Keyboard.Modifiers &
System.Windows.Input.ModifierKeys.Alt) != 0);
ApplicationContext Property
♦ My.Application.ApplicationContext
Returns the application context for the current application or thread.
VISUAL BASIC
Dim result As System.Windows.Forms.ApplicationContext =
My.Application.ApplicationContext
If you start a Windows Forms application by passing in a custom context, this instance is normally not accessible within the application. You must preserve a reference to it in your code if you want to access later.
C#
static class Program
{
// ----- Assumes that a LocalContext class derived
// from System.Windows.Forms.ApplicationContext
// has been defined elsewhere.
private static LocalContext TheContext = null;
[STAThread]
static void Main()
{
Program.TheContext = new LocalContext();
Program.TheContext.MainForm = new Form1();
Application.Run(Program.TheContext);
}
public static LocalContext GetContext
{
get
{
return Program.TheContext;
}
}
}
AssemblyName Property
♦ My.Application.Info.AssemblyName
Retrieves the simple name of the assembly, with the file extension removed.
VISUAL BASIC
Dim result As String = My.Application.Info.AssemblyName
C#
System.Reflection.Assembly currentAssembly =
System.Reflection.Assembly.GetEntryAssembly();
if (currentAssembly == null) currentAssembly =
System.Reflection.Assembly.GetCallingAssembly();
string result = currentAssembly.GetName().Name;
Audio Object
♦ My.Computer.Audio
See
Play Method, PlaySystemSound Method, Stop Method
AvailablePhysicalMemory Property
♦ My.Computer.Info.AvailablePhysicalMemory
Returns the total number of free bytes of physical memory on the local computer.
VISUAL BASIC
Dim result As ULong =
My.Computer.Info.AvailablePhysicalMemory
C#
// ----- GetMemoryInfo code discussed below.
ulong result = MemoryQuery.GetMemoryInfo().AvailPhysical;
Visual Basic retrieves memory information through the GlobalMemoryStatusEx Windows API call. The following code wraps the API call in C# code, and returns a Win32-compatible structure containing the memory information.
C#
// ----- This code works only with Windows 2000 and beyond.
public class MemoryQuery
{
[System.Runtime.InteropServices.StructLayoutAttribute(
System.Runtime.InteropServices.LayoutKind.
Sequential)]
public struct MemoryInfo
{
public uint DataLength;
public uint MemoryLoad;
public ulong TotalPhysical;
public ulong AvailPhysical;
public ulong TotalPageFile;
public ulong AvailPageFile;
public ulong TotalVirtual;
public ulong AvailVirtual;
public ulong AvailExtendedVirtual;
public void Initialize()
{
// ----- The API must know the return size.
this.DataLength = (uint)System.Runtime.
InteropServices.Marshal.SizeOf(
typeof(MemoryInfo));
}
}
[System.Runtime.InteropServices.DllImportAttribute(
"kernel32.dll", EntryPoint="GlobalMemoryStatusEx")]
[return: System.Runtime.InteropServices.
MarshalAsAttribute(System.Runtime.
InteropServices.UnmanagedType.Bool)]
public static extern bool GlobalMemoryStatusEx(
[System.Runtime.InteropServices.OutAttribute()]
out MemoryInfo memoryDetails);
public static MemoryInfo GetMemoryInfo()
{
MemoryQuery.MemoryInfo memoryDetails =
new MemoryQuery.MemoryInfo();
memoryDetails.Initialize();
if (MemoryQuery.GlobalMemoryStatusEx(
out memoryDetails))
return memoryDetails;
else
throw new System.Exception(
"Failed to retrieve memory information.");
}
}
AvailableVirtualMemory Property
♦ My.Computer.Info.AvailableVirtualMemory
Returns the total number of free bytes of virtual memory on the local computer.
VISUAL BASIC
Dim result As ULong =
My.Computer.Info.AvailableVirtualMemory
C#
// ----- GetMemoryInfo code discussed below.
ulong result = MemoryQuery.GetMemoryInfo().AvailVirtual;
Visual Basic retrieves memory information through the GlobalMemoryStatusEx Windows API call. See the “AvailablePhysicalMemory Property” entry in this chapter for a sample GetMemoryInfo method that wraps the API call in C# code.
ButtonsSwapped Property
♦ My.Computer.Mouse.ButtonsSwapped
Indicates whether the standard arrangement of the two primary mouse buttons has been reversed.
VISUAL BASIC
Dim result As Boolean = My.Computer.Mouse.ButtonsSwapped
C#
// ----- For Windows Forms code:
bool result = System.Windows.Forms.SystemInformation.
MouseButtonsSwapped;
// ----- For XAML-centric code:
bool result = System.Windows.SystemParameters.SwapButtons;
CapsLock Property
♦ My.Computer.Keyboard.CapsLock
Indicates whether the Caps Lock key is currently activated.
VISUAL BASIC
Dim result As Boolean = My.Computer.Keyboard.CapsLock
C#
// ----- For Windows Forms code:
bool result = System.Windows.Forms.Form.IsKeyLocked(
System.Windows.Forms.Keys.CapsLock);
// ----- For XAML-centric code:
bool result = System.Windows.Input.Keyboard.IsKeyToggled(
System.Windows.Input.Key.CapsLock);
ChangeCulture Method
♦ My.Application.ChangeCulture
Given a culture code (such as en-US), changes the current culture used for formatting certain values, such as numbers and dates.
VISUAL BASIC
My.Application.ChangeCulture("en-US")
C#
System.Threading.Thread.CurrentThread.CurrentCulture =
new System.Globalization.CultureInfo("en-US");
ChangeUICulture Method
♦ My.Application.ChangeUICulture
Given a culture code (such as en-US), changes the current culture used for the user interface.
VISUAL BASIC
My.Application.ChangeUICulture("en-US")
C#
System.Threading.Thread.CurrentThread.CurrentUICulture =
new System.Globalization.CultureInfo("en-US");
ClassesRoot Property
♦ My.Computer.Registry.ClassesRoot
Returns a reference to the HKEY_CLASSES_ROOT Windows registry location.
VISUAL BASIC
Dim result As Microsoft.Win32.RegistryKey =
My.Computer.Registry.ClassesRoot
C#
Microsoft.Win32.RegistryKey result =
Microsoft.Win32.Registry.ClassesRoot;
Clear Method
♦ My.Computer.Clipboard.Clear
Removes all data from the system clipboard.
VISUAL BASIC
My.Computer.Clipboard.Clear()
C#
// ----- For Windows Forms code:
System.Windows.Forms.Clipboard.Clear();
// ----- For XAML-centric code:
System.Windows.Clipboard.Clear();
Clipboard Object
♦ My.Computer.Clipboard
See
Clear Method, ContainsAudio Method, ContainsData Method, ContainsFileDropList Method, ContainsImage Method, ContainsText Method, GetAudioStream Method, GetData Method, GetDataObject Method, GetFileDropList Method, GetImage Method, GetText Method, SetAudio Method, SetData Method, SetDataObject Method,SetFileDropList Method, SetImage Method, SetText Method
Clock Object
♦ My.Computer.Clock
See
GmtTime Property, LocalTime Property, TickCount Property
CombinePath Method
♦ My.Computer.FileSystem.CombinePath
Combines an absolute path, such as a directory, with an additional relative path, such as a file name, adding the appropriate punctuation.
VISUAL BASIC
Dim result As String = My.Computer.FileSystem.CombinePath(
"C:\temp", "OutputFile.txt")
C#
string result = System.IO.Path.Combine(
"C:\\temp", "OutputFile.txt");
CommandLineArgs Property
♦ My.Application.CommandLineArgs
Returns a collection of the command-line arguments used to initiate the application. The application path is not included as the first element; only the arguments themselves are included, if any.
VISUAL BASIC
' ----- This code returns a read-only collection of
' the command-line arguments, excluding the
' program itself.
Dim result As System.Collections.ObjectModel.
ReadOnlyCollection(Of String) =
My.Application.CommandLineArgs
C#
// ----- This code returns an ordinary string array of
// the command-line arguments, *including* the
// program itself as the zeroth array element.
string[] result = System.Environment.GetCommandLineArgs();
CompanyName Property
♦ My.Application.Info.CompanyName
Returns the company name as stored in the assembly.
VISUAL BASIC
Dim result As String = My.Application.Info.CompanyName
C#
string result;
System.Reflection.Assembly currentAssembly =
System.Reflection.Assembly.GetEntryAssembly();
if (currentAssembly == null) currentAssembly =
System.Reflection.Assembly.GetCallingAssembly();
object[] attrSet = currentAssembly.GetCustomAttributes(
typeof(System.Reflection.AssemblyCompanyAttribute),
inherit:true);
if (attrSet.Length == 0)
result = "";
else
result = ((System.Reflection.AssemblyCompanyAttribute)
attrSet[0]).Company;
Computer Object
♦ My.Computer
See
Audio Object, Clipboard Object, Clock Object, FileSystem Object, Info Object (My.Computer), Keyboard Object, Mouse Object, Name Property (My.Computer), Network Object, Ports Object, Registry Object, Screen Property
ContainsAudio Method
♦ My.Computer.Clipboard.ContainsAudio
Indicates whether the system clipboard contains audio data.
VISUAL BASIC
Dim result As Boolean =
My.Computer.Clipboard.ContainsAudio()
C#
// ----- For Windows Forms code:
bool result =
System.Windows.Forms.Clipboard.ContainsAudio();
// ----- For XAML-centric code:
bool result = System.Windows.Clipboard.ContainsAudio();
ContainsData Method
♦ My.Computer.Clipboard.ContainsData
Indicates whether the system clipboard contains content with a specific data format.
VISUAL BASIC
Dim result As Boolean = My.Computer.Clipboard.ContainsData(
"CustomerRecord")
C#
// ----- For Windows Forms code:
bool result = System.Windows.Forms.Clipboard.ContainsData(
"CustomerRecord");
// ----- For XAML-centric code:
bool result = System.Windows.Clipboard.ContainsData(
"CustomerRecord");
ContainsFileDropList Method
♦ My.Computer.Clipboard.ContainsFileDropList
Indicates whether the system clipboard contains a list of target file paths.
VISUAL BASIC
Dim result As Boolean = My.Computer.Clipboard.
ContainsFileDropList()
C#
// ----- For Windows Forms code:
bool result = System.Windows.Forms.Clipboard.
ContainsFileDropList();
// ----- For XAML-centric code:
bool result =
System.Windows.Clipboard.ContainsFileDropList();
ContainsImage Method
♦ My.Computer.Clipboard.ContainsImage
Indicates whether the system clipboard contains image data.
VISUAL BASIC
Dim result As Boolean =
My.Computer.Clipboard.ContainsImage()
C#
// ----- For Windows Forms code:
bool result =
System.Windows.Forms.Clipboard.ContainsImage();
// ----- For XAML-centric code:
bool result = System.Windows.Clipboard.ContainsImage();
ContainsText Method
♦ My.Computer.Clipboard.ContainsText
Indicates whether the system clipboard contains text, optionally in a specified format.
VISUAL BASIC
Dim result As Boolean =
My.Computer.Clipboard.ContainsText()
C#
// ----- For Windows Forms code:
bool result =
System.Windows.Forms.Clipboard.ContainsText();
// ----- For XAML-centric code:
bool result = System.Windows.Clipboard.ContainsText();
The ContainsText method accepts one optional argument that indicates the type of text to check, such as HTML or Unicode. In the My and Windows Forms versions of the code, this argument is of type System.Windows.Forms.TextDataFormat; for XAML code, use the System.Windows.TextDataFormat enumeration instead.
CopyDirectory Method
♦ My.Computer.FileSystem.CopyDirectory
Copies a directory and all files within it to a new destination directory.
VISUAL BASIC
' ----- Basic syntax. Third (optional) argument is
' the overwrite flag.
My.Computer.FileSystem.CopyDirectory(
source, destination, True)
' ----- UI-invoking syntax.
My.Computer.FileSystem.CopyDirectory(source, destination,
UIOption.OnlyErrorDialogs)
C# does not include a feature that will copy a complete directory. For basic directory copy operations, your code must manually create the target directory and copy each file and subdirectory within the source directory to the target using features in the System.IOnamespace.
C#
private void CopyDirectory(string source,
string destination)
{
string destItem;
// ----- Create the target directory.
System.IO.Directory.CreateDirectory(destination);
// ----- Scan each source file.
foreach (string oneFile in System.IO.
Directory.GetFiles(source))
{
// ----- Copy a file to the target.
destItem = System.IO.Path.Combine(destination,
System.IO.Path.GetFileName(oneFile));
System.IO.File.Copy(oneFile, destItem);
}
// ----- Scan each source subdirectory.
foreach (string oneDirectory in System.IO.
Directory.GetDirectories(source))
{
// ----- Recurse to copy the subdirectory.
destItem = System.IO.Path.Combine(destination,
System.IO.Path.GetFileName(oneDirectory));
CopyDirectory(oneDirectory, destItem);
}
}
C# does not include features that invoke the Windows directory copy dialog. Instead, you must access the Win32 API directly and call the appropriate function. In the case of directory copying and similar file-based actions, you call the SHFileOperation API. See the “CopyFile Method” entry in this chapter for sample code that calls this API.
CopyFile Method
♦ My.Computer.FileSystem.CopyFile
Copies a file to a new location.
VISUAL BASIC
' ----- Basic syntax. Third (optional) argument is
' the overwrite flag.
My.Computer.FileSystem.CopyFile(source, destination, True)
' ----- UI-invoking syntax.
My.Computer.FileSystem.CopyFile(source, destination,
UIOption.OnlyErrorDialogs)
For basic file copy operations, the File.Copy method in the System.IO namespace provides functionality similar to the basic VB syntax.
C#
// ----- Third argument is the "overwrite" flag.
System.IO.File.Copy(source, destination, true);
C# does not include features that invoke the Windows file copy dialog. Instead, you must access the Win32 API directly and call the appropriate function. In the case of file copying and similar file-based actions, you call the SHFileOperation API. The following code shows how to call this method to perform a basic file copy.
C#
using System;
using System.Runtime.InteropServices;
public class FileCopy
{
// ----- Type of shell operation.
private enum FileFuncFlags : uint
{
FO_MOVE = 0x1,
FO_COPY = 0x2,
FO_DELETE = 0x3,
FO_RENAME = 0x4
}
// ----- Additional flags for some operations.
[Flags] public enum FileOpFlags : ushort
{
FOF_MULTIDESTFILES = 0x1,
FOF_CONFIRMMOUSE = 0x2,
FOF_SILENT = 0x4,
FOF_RENAMEONCOLLISION = 0x8,
FOF_NOCONFIRMATION = 0x10,
FOF_WANTMAPPINGHANDLE = 0x20,
FOF_ALLOWUNDO = 0x40,
FOF_FILESONLY = 0x80,
FOF_SIMPLEPROGRESS = 0x100,
FOF_NOCONFIRMMKDIR = 0x200,
FOF_NOERRORUI = 0x400,
FOF_NOCOPYSECURITYATTRIBS = 0x800,
FOF_NORECURSION = 0x1000,
FOF_NO_CONNECTED_ELEMENTS = 0x2000,
FOF_WANTNUKEWARNING = 0x4000,
FOF_NORECURSEREPARSE = 0x8000
}
// ----- Structure for operation details.
[StructLayout(LayoutKind.Sequential,
CharSet=CharSet.Unicode)]
private struct SHFILEOPSTRUCT
{
public IntPtr hwnd;
public FileFuncFlags wFunc;
[MarshalAs(UnmanagedType.LPWStr)]
public string pFrom;
[MarshalAs(UnmanagedType.LPWStr)]
public string pTo;
public FileOpFlags fFlags;
[MarshalAs(UnmanagedType.Bool)]
public bool fAnyOperationsAborted;
public IntPtr hNameMappings;
[MarshalAs(UnmanagedType.LPWStr)]
public string lpszProgressTitle;
}
// ----- Main shell file operation method.
[DllImport("shell32.dll",CharSet = CharSet.Unicode)]
static extern int SHFileOperation(
[In] ref SHFILEOPSTRUCT lpFileOp);
public static void CopyFiles(
string sourceFile, string destination)
{
// ----- Copy a file using the Windows copy.
SHFILEOPSTRUCT fileDetail;
int result;
fileDetail.wFunc = FileFuncFlags.FO_COPY;
fileDetail.fFlags = FileOpFlags.FOF_ALLOWUNDO;
fileDetail.pFrom = sourceFile + "\0\0";
fileDetail.pTo = destination + "\0\0";
fileDetail.hwnd = IntPtr.Zero;
fileDetail.fAnyOperationsAborted = false;
fileDetail.hNameMappings = IntPtr.Zero;
fileDetail.lpszProgressTitle = "";
try
{
result = SHFileOperation(ref fileDetail);
if (result != 0)
System.Windows.Forms.MessageBox.Show(
"Error occurred during copy.");
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(
ex.Message);
}
}
}
Microsoft’s MSDN web site (msdn.microsoft.com) includes full documentation on this and other “shell” features.
Copyright Property
♦ My.Application.Info.Copyright
Returns the copyright owner notice as stored in the assembly.
VISUAL BASIC
Dim result As String = My.Application.Info.Copyright
C#
string result;
System.Reflection.Assembly currentAssembly =
System.Reflection.Assembly.GetEntryAssembly();
if (currentAssembly == null) currentAssembly =
System.Reflection.Assembly.GetCallingAssembly();
object[] attrSet = currentAssembly.GetCustomAttributes(
typeof(System.Reflection.AssemblyCopyrightAttribute),
inherit:true);
if (attrSet.Length == 0)
result = "";
else
result = ((System.Reflection.
AssemblyCopyrightAttribute)attrSet[0]).Copyright;
CreateDirectory Method
♦ My.Computer.FileSystem.CreateDirectory
Creates the directory and subdirectories in a path.
VISUAL BASIC
My.Computer.FileSystem.CreateDirectory("C:\temp")
C#
System.IO.Directory.CreateDirectory("C:\\temp");
CtrlKeyDown Property
♦ My.Computer.Keyboard.CtrlKeyDown
Indicates whether a Control key is currently pressed.
VISUAL BASIC
Dim result As Boolean = My.Computer.Keyboard.CtrlKeyDown
C#
// ----- For Windows Forms code:
bool result = ((System.Windows.Forms.Control.ModifierKeys &
System.Windows.Forms.Keys.Control) != 0);
// ----- For XAML-centric code:
bool result = ((System.Windows.Input.Keyboard.Modifiers &
System.Windows.Input.ModifierKeys.Control) != 0);
Culture Property
♦ My.Application.Culture
Returns an object that describes the active data-formatting culture for numbers, dates, and other values.
VISUAL BASIC
Dim result As System.Globalization.CultureInfo =
My.Application.Culture
C#
System.Globalization.CultureInfo result =
System.Threading.Thread.CurrentThread.CurrentCulture;
CurrentConfig Property
♦ My.Computer.Registry.CurrentConfig
Returns a reference to the HKEY_CURRENT_CONFIG Windows registry location.
VISUAL BASIC
Dim result As Microsoft.Win32.RegistryKey =
My.Computer.Registry.CurrentConfig
C#
Microsoft.Win32.RegistryKey result =
Microsoft.Win32.Registry.CurrentConfig;
CurrentDirectory Property
♦ My.Computer.FileSystem.CurrentDirectory
Returns the full path to the directory used for relative directory references.
VISUAL BASIC
Dim result As String =
My.Computer.FileSystem.CurrentDirectory
C#
string result = System.IO.Directory.GetCurrentDirectory();
CurrentPrincipal Property
♦ My.User.CurrentPrincipal
Returns the in-effect security context.
VISUAL BASIC
Dim result As System.Security.Principal.IPrincipal =
My.User.CurrentPrincipal
C#
System.Security.Principal.IPrincipal result =
System.Threading.Thread.CurrentPrincipal;
CurrentUser Property
♦ My.Computer.Registry.CurrentUser
Returns a reference to the HKEY_CURRENT_USER Windows registry location.
VISUAL BASIC
Dim result As Microsoft.Win32.RegistryKey =
My.Computer.Registry.CurrentUser
C#
Microsoft.Win32.RegistryKey result =
Microsoft.Win32.Registry.CurrentUser;
CurrentUserApplicationData Property
♦ My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData
Returns the path to the “application data” folder for the current user.
VISUAL BASIC
Dim result As String = My.Computer.FileSystem.
SpecialDirectories.CurrentUserApplicationData
C#
string result = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.ApplicationData);
DefaultFileLogWriter Property
♦ My.Application.Log.DefaultFileLogWriter (for Desktop applications)
♦ My.Log.DefaultFileLogWriter (for ASP.NET applications)
C# applications do not configure logging features by default. Therefore, there is no default listener for logging purposes.
See Also
TraceSource Property
DeleteDirectory Method
♦ My.Computer.FileSystem.DeleteDirectory
Deletes a directory or moves it to the Recycle Bin.
VISUAL BASIC
' ----- Basic syntax. Directory is deleted permanently.
My.Computer.FileSystem.DeleteDirectory(targetDirectory,
DeleteDirectoryOption.DeleteAllContents)
' ----- UI-invoking syntax.
My.Computer.FileSystem.DeleteDirectory(targetDirectory,
UIOption.OnlyErrorDialogs,
RecycleOption.SendToRecycleBin)
For basic directory delete operations, the Directory.Delete method in the System.IO namespace provides functionality comparable to the basic VB syntax.
C#
// ----- Directory is deleted permanently. The
// second argument deletes even when the
// target is not empty.
System.IO.Directory.Delete(targetFile, true);
C# does not include features that invoke the Windows directory delete dialog. Instead, you must access the Win32 API directly and call the appropriate function. In the case of directory removal and similar file-based actions, you call the SHFileOperation API. See the “CopyFile Method” entry in this chapter for sample code that calls this API.
DeleteFile Method
♦ My.Computer.FileSystem.DeleteFile
Deletes a file or moves it to the Recycle Bin.
VISUAL BASIC
' ----- Basic syntax. File is deleted permanently.
My.Computer.FileSystem.DeleteFile(targetFile)
' ----- UI-invoking syntax.
My.Computer.FileSystem.DeleteFile(targetFile,
UIOption.OnlyErrorDialogs,
RecycleOption.SendToRecycleBin)
For basic file delete operations, the File.Delete method in the System.IO namespace provides functionality comparable to the basic VB syntax.
C#
// ----- File is deleted permanently.
System.IO.File.Delete(targetFile);
C# does not include features that invoke the Windows file delete dialog. Instead, you must access the Win32 API directly and call the appropriate function. In the case of file removal and similar file-based actions, you call the SHFileOperation API. See the “CopyFile Method” entry in this chapter for sample code that calls this API.
Deployment Property
♦ My.Application.Deployment
Returns the current application’s ClickOnce (installation) deployment object.
VISUAL BASIC
Dim result As System.Deployment.Application.
ApplicationDeployment = My.Application.Deployment
C#
System.Deployment.Application.ApplicationDeployment
result = System.Deployment.Application.
ApplicationDeployment.CurrentDeployment;
Description Property
♦ My.Application.Info.Description
Returns the application description as stored in the assembly.
VISUAL BASIC
Dim result As String = My.Application.Info.Description
C#
string result;
System.Reflection.Assembly currentAssembly =
System.Reflection.Assembly.GetEntryAssembly();
if (currentAssembly == null) currentAssembly =
System.Reflection.Assembly.GetCallingAssembly();
object[] attrSet = currentAssembly.GetCustomAttributes(
typeof(System.Reflection.AssemblyDescriptionAttribute),
inherit:true);
if (attrSet.Length == 0)
result = "";
else
result = ((System.Reflection.
AssemblyDescriptionAttribute)
attrSet[0]).Description;
Desktop Property
♦ My.Computer.FileSystem.SpecialDirectories.Desktop
Returns the path to the “desktop” folder for the current user.
VISUAL BASIC
Dim result As String = My.Computer.FileSystem.
SpecialDirectories.Desktop
C#
string result = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.DesktopDirectory);
DirectoryExists Method
♦ My.Computer.FileSystem.DirectoryExists
Indicates whether a directory path exists.
VISUAL BASIC
Dim result As Boolean = My.Computer.FileSystem.
DirectoryExists("C:\temp")
C#
bool result = System.IO.Directory.Exists("C:\\temp");
DirectoryPath Property
♦ My.Application.Info.DirectoryPath
Returns the path for the directory containing the current application.
VISUAL BASIC
Dim result As String = My.Application.Info.DirectoryPath
C#
System.Reflection.Assembly currentAssembly =
System.Reflection.Assembly.GetEntryAssembly();
if (currentAssembly == null) currentAssembly =
System.Reflection.Assembly.GetCallingAssembly();
string result = System.IO.Path.GetDirectoryName(
currentAssembly.Location);
DoEvents Method
♦ My.Application.DoEvents
In Windows Forms applications, temporarily suspends the current code to allow processing of messages in other threads and processes.
VISUAL BASIC
My.Application.DoEvents()
C#
// ----- For Windows Forms code only:
System.Windows.Forms.Application.DoEvents();
XAML-based applications use a “dispatcher” or a “background worker thread” to achieve this same purpose.
DownloadFile Method
♦ My.Computer.Network.DownloadFile
Downloads a file from a network address to the local computer.
VISUAL BASIC
My.Computer.Network.DownloadFile(sourceAddress,
destinationFile, userName, password);
C#
System.Net.WebClient client = new System.Net.WebClient();
System.Uri sourceUri = new System.Uri(sourceAddress);
// ----- Default credentials.
client.UseDefaultCredentials = true;
// ----- Or, supply specific credentials.
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(
userName, password);
// ----- Synchronous copy.
client.DownloadFile(sourceUri, destinationFile);
// ----- Or, asynchronous copy, providing your own
// custom complete/cancel event handler.
client.DownloadFileCompleted += new
AsyncCompletedEventHandler(CompletedCallback);
client.DownloadFileAsync(sourceUri, destinationFile);
The WebClient class’ download methods will overwrite the target file if it exists. You must manually check for the file if you do not want it overwritten. Also, it provides no visual cues as to the state of the transfer. You must provide your own progress dialog if desired.
To override the default timeout value, derive a new class from the WebClient class, and manually configure the WebRequest’s TimeOut property. Then use this class instead of the standard WebClient class to perform the download.
C#
class WebClientTimeout : System.Net.WebClient
{
public int Timeout { get; set; }
public WebClientTimeout(int timeoutOverride)
{
// ----- Save the user-specified timeout.
this.Timeout = timeoutOverride;
}
protected override System.Net.WebRequest
GetWebRequest(System.Uri sourceAddress)
{
// ----- Modify the request with the timeout.
System.Net.WebRequest coreRequest =
base.GetWebRequest(sourceAddress);
if (coreRequest != null)
coreRequest.Timeout = this.Timeout;
return coreRequest;
}
}
Drives Property
♦ My.Computer.FileSystem.Drives
Returns a collection of objects describing the workstation’s logical disk drives.
VISUAL BASIC
' ----- This code returns a read-only collection of drives.
Dim result As System.Collections.ObjectModel.
ReadOnlyCollection(Of System.IO.DriveInfo) =
My.Computer.FileSystem.Drives
C#
// ----- This code returns an ordinary array of drives.
System.IO.DriveInfo[] result =
System.IO.DriveInfo.GetDrives();
DynData Property
♦ My.Computer.Registry.DynData
Returns a reference to the HKEY_DYN_DATA Windows registry location.
VISUAL BASIC
' ----- This code is obsolete.
Dim result As Microsoft.Win32.RegistryKey =
My.Computer.Registry.DynData
C#
// ----- This code is obsolete.
Microsoft.Win32.RegistryKey result =
Microsoft.Win32.Registry.DynData;
This code is useful only on Windows 98 and Windows ME platforms. It is not valid on Windows NT-based systems or later.
FileExists Method
♦ My.Computer.FileSystem.FileExists
Indicates whether a file path exists.
VISUAL BASIC
Dim result As Boolean = My.Computer.FileSystem.FileExists(
"C:\temp\WorkFile.txt")
C#
bool result = System.IO.File.Exists(
"C:\\temp\\WorkFile.txt");
FileSystem Object
♦ My.Computer.FileSystem
See
CombinePath Method, CopyDirectory Method, CopyFile Method, CreateDirectory Method, CurrentDirectory Property, DeleteDirectory Method, DeleteFile Method, DirectoryExists Method, Drives Property, FileExists Method, FindInFiles Method, GetDirectories Method, GetDirectoryInfo Method, GetDriveInfo Method, GetFileInfo Method, GetFiles Method, GetName Method, GetParentPath Method, GetTempFileName Method, MoveDirectory Method, MoveFile Method, OpenTextFieldParser Method, OpenTextFileReader Method, OpenTextFileWriter Method, ReadAllBytes Method, ReadAllText Method, RenameDirectory Method, RenameFile Method, SpecialDirectories Object, WriteAllBytes Method, WriteAllText Method
FindInFiles Method
♦ My.Computer.FileSystem.FindInFiles
Returns a collection of file paths from a target directory that contains a specified search string.
VISUAL BASIC
Dim result As System.Collections.ObjectModel.
ReadOnlyCollection(Of String) =
My.Computer.FileSystem.FindInFiles(targetDirectory,
searchText, ignoreCase,
SearchOption.SearchAllSubDirectories, "*.txt")
C# does not include an equivalent for VB’s FindInFiles method. Instead, you must examine each file in a target directory to see if it contains the search string. The following code provides one example of how you can search for matches.
C#
private static List<string> FindInFiles(
string targetDirectory, string searchText,
bool ignoreCase, System.IO.SearchOption depthType,
string fileMask = "*.*")
{
List<string> results = new List<string>();
bool foundMatch;
string content;
foreach (string oneFile
in System.IO.Directory.GetFiles(
targetDirectory, fileMask, depthType))
{
// ----- WARNING: Large files could fill memory.
content = System.IO.File.ReadAllText(oneFile);
if (ignoreCase)
foundMatch = content.ToUpper().Contains(
searchText.ToUpper());
else
foundMatch = content.Contains(searchText);
if (foundMatch)
results.Add(oneFile);
}
return results;
}
Forms Object
♦ My.Forms
Provides access to any form within the current Windows Forms project.
VISUAL BASIC
' ----- Full syntax
My.Forms.Form1.Show()
' ----- Shortened syntax
Form1.Show()
Windows Forms applications written in C# do not maintain a list of the current active or available forms within the project. Each form must be manually instantiated, and any monitoring of all active forms must be done through custom code.
GetAudioStream Method
♦ My.Computer.Clipboard.GetAudioStream
Returns a stream object of audio data from the system clipboard.
VISUAL BASIC
Dim result As System.IO.Stream =
My.Computer.Clipboard.GetAudioStream()
C#
// ----- For Windows Forms code:
System.IO.Stream result = System.Windows.Forms.
Clipboard.GetAudioStream();
// ----- For XAML-centric code:
System.IO.Stream result = System.Windows.
Clipboard.GetAudioStream();
GetData Method
♦ My.Computer.Clipboard.GetData
Returns an object from the system clipboard in the specified format.
VISUAL BASIC
Dim result As Object = My.Computer.Clipboard.
GetData("MyAppFormat")
C#
// ----- For Windows Forms code:
object result = System.Windows.Forms.Clipboard.
GetData("MyAppFormat");
// ----- For XAML-centric code:
object result = System.Windows.Clipboard.
GetData("MyAppFormat");
GetDataObject Method
♦ My.Computer.Clipboard.GetDataObject
Returns an object from the system clipboard that supports the IDataObject interface. When the clipboard contains data in multiple formats at once, this interface provides access to each of those formats.
VISUAL BASIC
Dim result As System.Windows.Forms.IDataObject =
My.Computer.Clipboard.GetDataObject()
C#
// ----- For Windows Forms code:
System.Windows.Forms.IDataObject result =
System.Windows.Forms.Clipboard.GetDataObject();
// ----- For XAML-centric code:
System.Windows.IDataObject result =
System.Windows.Clipboard.GetDataObject();
GetDirectories Method
♦ My.Computer.FileSystem.GetDirectories
Returns a collection of directory names in a specified directory, optionally checking in subdirectories, and optionally matching a pattern.
VISUAL BASIC
' ----- Return directories starting with "A" in
' the target directory, ignore subdirectories.
Dim result As ReadOnlyCollection(Of String) =
My.Computer.FileSystem.GetDirectories(
"C:\WorkArea", SearchOption.SearchTopLevelOnly, "A*")
C#
// ----- Return directories starting with "A" in
// the target directory, ignore subdirectories.
string[] result = System.IO.Directory.GetDirectories(
"C:\\WorkArea", "A*",
System.IO.SearchOption.TopDirectoryOnly);
As shown in this sample code, the C# equivalent returns an array of strings instead of a collection.
GetDirectoryInfo Method
♦ My.Computer.FileSystem.GetDirectoryInfo
Returns an informational object for the indicated directory.
VISUAL BASIC
Dim result As System.IO.DirectoryInfo =
My.Computer.FileSystem.GetDirectoryInfo("C:\temp")
C#
System.IO.DirectoryInfo result =
new System.IO.DirectoryInfo("C:\\temp");
GetDriveInfo Method
♦ My.Computer.FileSystem.GetDriveInfo
Returns an informational object for the indicated drive letter.
VISUAL BASIC
Dim result As System.IO.DriveInfo =
My.Computer.FileSystem.GetDriveInfo("C:")
C#
System.IO.DriveInfo result = new System.IO.DriveInfo("C:");
GetEnvironmentVariable Method
♦ My.Application.GetEnvironmentVariable
Retrieves the value of the specified Windows environment variable.
VISUAL BASIC
' ----- Throws an exception if the variable is not found.
Dim result As String =
My.Application.GetEnvironmentVariable("PATH")
C#
// ----- Returns null if the variable is not found.
string result = System.Environment.
GetEnvironmentVariable("PATH");
GetFileDropList Method
♦ My.Computer.Clipboard.GetFileDropList
Returns a collection of file-path strings from the system clipboard.
VISUAL BASIC
Dim result As System.Collections.
Specialized.StringCollection =
My.Computer.Clipboard.GetFileDropList()
C#
// ----- For Windows Forms code:
System.Collections.Specialized.StringCollection result =
System.Windows.Forms.Clipboard.GetFileDropList();
// ----- For XAML-centric code:
System.Collections.Specialized.StringCollection result =
System.Windows.Clipboard.GetFileDropList();
GetFileInfo Method
♦ My.Computer.FileSystem.GetFileInfo
Returns an informational object for the indicated file.
VISUAL BASIC
Dim result As System.IO.FileInfo =
My.Computer.FileSystem.GetFileInfo(
"C:\temp\WorkFile.txt")
C#
System.IO.FileInfo result =
new System.IO.FileInfo("C:\\temp\\WorkFile.txt");
GetFiles Method
♦ My.Computer.FileSystem.GetFiles
Returns a collection of file names in a specified directory, optionally checking in subdirectories, and optionally matching a pattern.
VISUAL BASIC
' ----- Return text files with a .txt extension in
' the target directory, ignore subdirectories.
Dim result As ReadOnlyCollection(Of String) =
My.Computer.FileSystem.GetFiles("C:\WorkArea",
SearchOption.SearchTopLevelOnly, "*.txt")
C#
// ----- Return text files with a .txt extension in
// the target directory, ignore subdirectories.
string[] result =
System.IO.Directory.GetFiles("C:\\WorkArea", "*.txt",
System.IO.SearchOption.TopDirectoryOnly);
As shown in this sample code, the C# equivalent returns an array of strings instead of a collection.
GetImage Method
♦ My.Computer.Clipboard.GetImage
Returns an image from the system clipboard.
VISUAL BASIC
Dim result As System.Drawing.Image =
My.Computer.Clipboard.GetImage()
C#
// ----- For Windows Forms code:
System.Drawing.Image result =
System.Windows.Forms.Clipboard.GetImage();
// ----- For XAML-centric code:
System.Drawing.Image result =
System.Windows.Clipboard.GetImage();
GetName Method
♦ My.Computer.FileSystem.GetName
Returns the file name portion of a file path.
VISUAL BASIC
' ----- Returns "WorkFile.txt"
Dim result As String = My.Computer.FileSystem.GetName(
"C:\temp\WorkFile.txt")
C#
// ----- Returns "WorkFile.txt"
string result = System.IO.Path.GetFileName(
"C:\\temp\\WorkFile.txt");
GetParentPath Method
♦ My.Computer.FileSystem.GetParentPath
Returns the parent directory for a specified file or directory path.
VISUAL BASIC
' ----- Returns "C:\temp"
Dim result As String =
My.Computer.FileSystem.GetParentPath(
"C:\temp\WorkFile.txt")
C#
// ----- Returns "C:\temp"
string result = System.IO.Path.GetDirectoryName(
"C:\\temp\\WorkFile.txt");
GetParentPath accepts absolute or relative paths. The C# equivalent requires an absolute path.
GetTempFileName Method
♦ My.Computer.FileSystem.GetTempFileName
Creates a temporary file, and returns the path to that file.
VISUAL BASIC
Dim result As String =
My.Computer.FileSystem.GetTempFileName()
C#
string result = System.IO.Path.GetTempFileName();
GetText Method
♦ My.Computer.Clipboard.GetText
Returns text from the system clipboard.
VISUAL BASIC
Dim result As String = My.Computer.Clipboard.GetText()
C#
// ----- For Windows Forms code:
string result = System.Windows.Forms.Clipboard.GetText();
// ----- For XAML-centric code:
string result = System.Windows.Clipboard.GetText();
The GetText method accepts one optional argument that indicates the type of text to check, such as HTML or Unicode. In the My and Windows Forms versions of the code, this argument is of type System.Windows.Forms.TextDataFormat; for XAML code, use theSystem.Windows.TextDataFormat enumeration instead. By default, the text is retrieved in Unicode format.
GetValue Method
♦ My.Computer.Registry.GetValue
Returns data from a specified Windows registry value.
VISUAL BASIC
Dim result As Long = CLng(My.Computer.Registry.GetValue(
"HKEY_CURRENT_USER\Software\Example\MyApp",
"ErrorCount", 0&))
C#
long result = (long)Microsoft.Win32.Registry.GetValue(
"HKEY_CURRENT_USER\\Software\\Example\\MyApp",
"ErrorCount", 0L);
GmtTime Property
♦ My.Computer.Clock.GmtTime
Returns the current date and time in the UTC (Universal Coordinated Time) time zone.
VISUAL BASIC
Dim result As Date = My.Computer.Clock.GmtTime
C#
DateTime result = DateTime.UtcNow;
Info Object (My.Application)
♦ My.Application.Info
See
AssemblyName Property, CompanyName Property, Copyright Property, Description Property, DirectoryPath Property, LoadedAssemblies Property, ProductName Property, StackTrace Property, Title Property, Trademark Property, Version Property, WorkingSet Property
Info Object (My.Computer)
♦ My.Computer.Info
See
AvailablePhysicalMemory PropertyAvailableVirtualMemory Property, InstalledUICulture Property, OSFullName Property, OSPlatform Property, OSVersion Property, TotalPhysicalMemory Property, TotalVirtualMemory Property
InitializeWithWindowsUser Method
♦ My.User.InitializeWithWindowsUser
Resets My.User to refer to the user that started the application.
VISUAL BASIC
My.User.InitializeWithWindowsUser()
C#
System.Threading.Thread.CurrentPrincipal =
new System.Security.Principal.WindowsPrincipal(
System.Security.Principal.WindowsIdentity.GetCurrent);
InstalledUICulture Property
♦ My.Computer.Info.InstalledUICulture
Returns an object that describes the user interface culture of the operating system.
VISUAL BASIC
Dim result As System.Globalization.CultureInfo =
My.Computer.Info.InstalledUICulture
C#
System.Globalization.CultureInfo result =
System.Globalization.CultureInfo.InstalledUICulture;
IsAuthenticated Property
♦ My.User.IsAuthenticated
Returns a value indicating the authentication status of the current user.
VISUAL BASIC
Dim result As Boolean = My.User.IsAuthenticated
C#
bool result = System.Threading.Thread.
CurrentPrincipal.Identity.IsAuthenticated;
IsAvailable Property
♦ My.Computer.Network.IsAvailable
Indicates whether a network connected to the local computer is available for use.
VISUAL BASIC
Dim result As Boolean = My.Computer.Network.IsAvailable
C#
bool result = System.Net.NetworkInformation.
NetworkInterface.GetIsNetworkAvailable();
IsInRole Method
♦ My.User.IsInRole
Returns a value indicating whether the current user belongs to the specified role.
VISUAL BASIC
' Option 1: Dim role As String = "Administrator"
' Option 2: Dim role As BuiltInRole =
' BuiltInRole.Administrator
Dim result As Boolean = My.User.IsInRole(role)
C#
// ----- Option 1: String-based lookup.
string role = "Administrator";
bool result = System.Threading.Thread.
CurrentPrincipal.IsInRole(role);
// ----- Option 2: Windows role-based lookup.
// Assumes: using System.Security.Principal;
bool result;
WindowsBuiltInRole role = WindowsBuiltInRole.Administrator;
IPrincipal activePrincipal =
System.Threading.Thread.CurrentPrincipal;
if (activePrincipal is WindowsPrincipal)
result = ((WindowsPrincipal)activePrincipal).
IsInRole(role);
else
{
TypeConverter converter = TypeDescriptor.GetConverter(
typeof(WindowsBuiltInRole));
result = activePrincipal.IsInRole(
converter.ConvertToString(role));
}
The My namespace includes a BuiltInRole enumeration that is closely related to the WindowsBuiltInRole enumeration indicated in the sample code. The members are identical, so it is valid to use the Windows-specific version in C# code. To check role membership for Windows users, you can use either the string-based or enumeration-based versions. For non-Windows role verifications, use the string version only.
IsNetworkDeployed Property
♦ My.Application.IsNetworkDeployed
Returns a value that indicates whether the application was deployed from a network using ClickOnce.
VISUAL BASIC
Dim result As Boolean = My.Application.IsNetworkDeployed
C#
bool result = System.Deployment.Application.
ApplicationDeployment.IsNetworkDeployed;
Keyboard Object
♦ My.Computer.Keyboard
See
AltKeyDown PropertyCapsLock Property, CtrlKeyDown Property, NumLock Property, ScrollLock Property, SendKeys Method, ShiftKeyDown Property
LoadedAssemblies Property
♦ My.Application.Info.LoadedAssemblies
Returns a collection of the current application’s loaded assemblies.
VISUAL BASIC
' ----- Returns a read-only collection of the results.
Dim result As System.Collections.ObjectModel.
ReadOnlyCollection(Of System.Reflection.Assembly) =
My.Application.Info.LoadedAssemblies
C#
// ----- Returns a standard array of the results.
System.Reflection.Assembly[] result =
AppDomain.CurrentDomain.GetAssemblies();
LocalMachine Property
♦ My.Computer.Registry.LocalMachine
Returns a reference to the HKEY_LOCAL_MACHINE Windows registry location.
VISUAL BASIC
Dim result As Microsoft.Win32.RegistryKey =
My.Computer.Registry.LocalMachine
C#
Microsoft.Win32.RegistryKey result =
Microsoft.Win32.Registry.LocalMachine;
LocalTime Property
♦ My.Computer.Clock.LocalTime
Returns the current date and time within the current time zone.
VISUAL BASIC
Dim result As Date = My.Computer.Clock.LocalTime
C#
DateTime result = DateTime.Now;
Log Object
♦ My.Application.Log (for Desktop applications)
♦ My.Log (for ASP.NET applications)
See
DefaultFileLogWriter Property, TraceSource Property, WriteEntry Method, WriteException Method
MinimumSplashScreenDisplayTime Property
♦ My.Application.MinimumSplashScreenDisplayTime
Specifies the minimum time, in milliseconds, that the splash screen should appear.
VISUAL BASIC
' ----- Show for at least two seconds.
My.Application.MinimumSplashScreenDisplayTime = 2000
This property is part of Visual Basic’s Windows Forms Application Framework, a set of classes not included in C# projects. There is no direct C# equivalent for the MinimumSplashScreenDisplayTime property. Instead, you must manage the display of any splash screen in your application by hand. See the “SplashScreen Property” entry in this chapter for additional information.
See Also
SplashScreen Property
Mouse Object
♦ My.Computer.Mouse
See
ButtonsSwapped Property, WheelExists Property, WheelScrollLines Property
MoveDirectory Method
♦ My.Computer.FileSystem.MoveDirectory
Moves a directory to a new location.
VISUAL BASIC
' ----- Basic syntax. Third (optional) argument is
' the overwrite flag.
My.Computer.FileSystem.MoveDirectory(
source, destination, True)
' ----- UI-invoking syntax.
My.Computer.FileSystem.MoveDirectory(source, destination,
UIOption.OnlyErrorDialogs)
For basic directory move operations, the Directory.Move method in the System.IO namespace provides functionality comparable to the basic VB syntax.
C#
// ----- Directory.Move lacks the overwrite option.
System.IO.Directory.Move(source, destination);
C# does not include features that invoke the Windows directory move dialog. Instead, you must access the Win32 API directly and call the appropriate function. In the case of directory moving and similar file-based actions, you call the SHFileOperation API. See the “CopyFile Method” entry in this chapter for sample code that calls this API.
MoveFile Method
♦ My.Computer.FileSystem.MoveFile
Moves a file to a new directory.
VISUAL BASIC
' ----- Basic syntax. Third (optional) argument is
' the overwrite flag.
My.Computer.FileSystem.MoveFile(source, destination, True)
' ----- UI-invoking syntax.
My.Computer.FileSystem.MoveFile(source, destination,
UIOption.OnlyErrorDialogs)
For basic file move operations, the File.Move method in the System.IO namespace provides functionality comparable to the basic VB syntax.
C#
// ----- File.Move lacks the overwrite option.
System.IO.File.Move(source, destination);
C# does not include features that invoke the Windows file move dialog. Instead, you must access the Win32 API directly and call the appropriate function. In the case of file moving and similar file-based actions, you call the SHFileOperation API. See the “CopyFile Method” entry in this chapter for sample code that calls this API.
My Namespace
♦ My
See
Application Object, Computer Object, Forms Object, Log Object (My), Request Object, Resources Object, Response Object, Settings Object, User Object, WebServices Object
MyDocuments Property
♦ My.Computer.FileSystem.SpecialDirectories.MyDocuments
Returns the path to the “documents” folder for the current user.
VISUAL BASIC
Dim result As String = My.Computer.FileSystem.
SpecialDirectories.MyDocuments
C#
string result = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.MyDocuments);
MyMusic Property
♦ My.Computer.FileSystem.SpecialDirectories.MyMusic
Returns the path to the “music” folder for the current user.
VISUAL BASIC
Dim result As String = My.Computer.FileSystem.
SpecialDirectories.MyMusic
C#
string result = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.MyMusic);
MyPictures Property
♦ My.Computer.FileSystem.SpecialDirectories.MyPictures
Returns the path to the “pictures” folder for the current user.
VISUAL BASIC
Dim result As String = My.Computer.FileSystem.
SpecialDirectories.MyPictures
C#
string result = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.MyPictures);
Name Property (My.Computer)
♦ My.Computer.Name
Returns the name of the local computer.
VISUAL BASIC
Dim result As String = My.Computer.Name
C#
string result = System.Environment.MachineName;
Name Property (My.User)
♦ My.User.Name
Returns the current Windows user name.
VISUAL BASIC
Dim result As String = My.User.Name
C#
string result = System.Threading.Thread.
CurrentPrincipal.Identity.Name;
Network Object
♦ My.Computer.Network
See
DownloadFile Method, IsAvailable Property, NetworkAvailabilityChanged Event (My.Computer.Network), Ping Method, UploadFile Method
NetworkAvailabilityChanged Event (My.Application)
♦ My.Application.NetworkAvailabilityChanged
This event is limited to Windows Forms applications. The same event as exposed through the My.Computer.Network class is identical in purpose, and is available to all application types. See that event’s entry for the C# equivalent for both VB events.
See Also
NetworkAvailabilityChanged Event (My.Computer.Network)
NetworkAvailabilityChanged Event (My.Computer.Network)
♦ My.Computer.Network.NetworkAvailabilityChanged
Calls an event handler when network availability changes.
VISUAL BASIC
' ----- Event handler logic.
Public Sub NetworkPresenceHandler(ByVal sender As Object,
ByVal e As NetworkAvailableEventArgs)
End Sub
' ----- Elsewhere, associating handler with event.
AddHandler My.Computer.Network.NetworkAvailabilityChanged,
AddressOf NetworkPresenceHandler
C#
// ----- Event handler logic.
public static void NetworkPresenceHandler(object sender,
System.Net.NetworkInformation.
NetworkAvailabilityEventArgs e)
{
}
// ----- Elsewhere, associating handler with event.
System.Net.NetworkInformation.NetworkChange
.NetworkAvailabilityChanged += NetworkPresenceHandler;
NumLock Property
♦ My.Computer.Keyboard.NumLock
Indicates whether the Num Lock key is currently activated.
VISUAL BASIC
Dim result As Boolean = My.Computer.Keyboard.NumLock
C#
// ----- For Windows Forms code:
bool result = System.Windows.Forms.Form.IsKeyLocked(
System.Windows.Forms.Keys.NumLock);
// ----- For XAML-centric code:
bool result = System.Windows.Input.Keyboard.IsKeyToggled(
System.Windows.Input.Key.NumLock);
OpenForms Property
♦ My.Application.OpenForms
Returns a collection of the forms currently open within a Windows Forms application.
VISUAL BASIC
Dim result As System.Windows.Forms.FormCollection =
My.Application.OpenForms
C#
System.Windows.Forms.FormCollection result =
System.Windows.Forms.Application.OpenForms;
OpenSerialPort Method
♦ My.Computer.Ports.OpenSerialPort
Opens a connection to a serial port on the local workstation.
VISUAL BASIC
Dim portAccess As System.IO.Ports.SerialPort =
My.Computer.Ports.OpenSerialPort(
portName, baudRate, parity, dataBits, stopBits)
C#
System.IO.Ports.SerialPort portAccess =
new System.IO.Ports.SerialPort(
portName, baudRate, parity, dataBits, stopBits);
OpenTextFieldParser Method
♦ My.Computer.FileSystem.OpenTextFieldParser
C# does not include a direct equivalent for the OpenTextFieldParser method, or the underlying TextFieldParser class that it employs. It is possible to add a reference to the Microsoft.VisualBasic assembly to a C# application and use these VB-targeted features. For applications that need to forgo access to all Visual Basic components, the equivalent functionality will need to be obtained from another source, or developed from scratch.
To open a file for reading in C#, open it as a stream using the appropriate encoding. Once opened, each line can be read in using the StreamReader class’ ReadLine method.
C#
string filePath = "C:\\temp\\FileWithFields.txt";
System.Text.Encoding useEncoding =
System.Text.Encoding.UTF8;
bool autoDetectEncoding = true;
System.IO.StreamReader inStream =
new System.IO.StreamReader(
filePath, useEncoding, autoDetectEncoding);
// ----- Later, in a loop.
string lineContent = inStream.ReadLine();
For fixed-width fields, extract specific portions of the line text.
C#
// ----- Line begins with a 2-character state followed
// by a 30-character city name.
string stateShort = lineContent.Substring(0, 2);
string cityName = lineContent.Substring(2, 30).Trim();
For delimited files that do not use text qualifiers around individual columns, use the string object’s Split method to get the individual fields.
C#
// ----- A tab-delimited file.
string[] allFields = lineContent.Split(new char[] {'\t'});
string stateShort = allFields[0];
string cityName = allFields[1];
For delimited files that include text qualifiers, with the optional inclusion of the delimiter within the quoted fields, you will need to process the characters of the line individually, or use some complex regular expressions that may vary based on the format of the input. The following code represents one way to parse the data, looking for quote-qualified comma-delimited strings.
C#
List<string> results = new List<string>();
int fieldPos = 0;
bool inQuote = false;
string tempField = "";
for (int counter = 0; counter < lineContent.Length;
counter++)
{
if (lineContent[counter] == ',')
{
// ----- Might be a new field or within quotes.
if (!inQuote)
{
// ----- Finished a field.
tempField = lineContent.Substring(
fieldPos, counter - fieldPos);
if ((tempField.Length >= 2) &&
(tempField.Substring(0, 1) == "\"") &&
(tempField.Substring(
tempField.Length - 1, 1) == "\""))
tempField = tempField.Substring(
1, tempField.Length - 2);
results.Add(tempField);
fieldPos = counter + 1;
}
}
else if (lineContent[counter] == '"')
{
// ----- Start or end a quoted field.
inQuote = !inQuote;
}
}
// ----- Finish the last field.
tempField = "";
if (lineContent.Length > fieldPos)
tempField = lineContent.Substring(fieldPos,
lineContent.Length - fieldPos);
if ((tempField.Length >= 2) &&
(tempField.Substring(0, 1) == "\"") &&
(tempField.Substring(
tempField.Length - 1, 1) == "\""))
tempField = tempField.Substring(1,
tempField.Length - 2);
results.Add(tempField);
string[] lineFields = results.ToArray();
This code does not handle all complex cases. For example, if a quoted field is surrounded by whitespace, the quotation marks will not be removed.
OpenTextFileReader Method
♦ My.Computer.FileSystem.OpenTextFileReader
Opens an existing file for text input.
VISUAL BASIC
Dim filePath As String = "C:\temp\WorkFile.txt"
Dim useEncoding As System.Text.Encoding =
System.Text.Encoding.UTF8
Dim result As System.IO.StreamReader =
My.Computer.FileSystem.OpenTextFileReader(
filePath, useEncoding)
C#
string filePath = "C:\\temp\\WorkFile.txt";
System.TextEncoding useEncoding =
System.Text.Encoding.UTF8;
bool autoDetectEncoding = true;
System.IO.StreamReader result = new System.IO.StreamReader(
filePath, useEncoding, autoDetectEncoding);
In Visual Basic, the encoding parameter is optional; when absent, output defaults to UTF8 encoding. The equivalent StreamReader class accepts a wider variety of parameter options in its constructor. See the Visual Studio documentation for these options.
OpenTextFileWriter Method
♦ My.Computer.FileSystem.OpenTextFileWriter
Opens an existing file, or creates a new one, for text output.
VISUAL BASIC
Dim filePath As String = "C:\temp\WorkFile.txt"
Dim appendIfFound As Boolean = True
Dim useEncoding As System.Text.Encoding =
System.Text.Encoding.UTF8
Dim result As System.IO.StreamWriter =
My.Computer.FileSystem.OpenTextFileWriter(
filePath, appendIfFound, useEncoding)
C#
string filePath = "C:\\temp\\WorkFile.txt";
bool appendIfFound = true;
System.TextEncoding useEncoding =
System.Text.Encoding.UTF8;
System.IO.StreamWriter result = new System.IO.StreamWriter(
filePath, appendIfFound, useEncoding);
In Visual Basic, the encoding parameter is optional; when absent, output defaults to UTF8 encoding. The equivalent StreamWriter class accepts a wider variety of parameter options in its constructor. See the Visual Studio documentation for these options.
OSFullName Property
♦ My.Computer.Info.OSFullName
Returns the full name of the operating system.
VISUAL BASIC
Dim result As String = My.Computer.Info.OSFullName
C#
// Assumes: using System.Management;
// ----- Default to My.Computer.Info.OSPlatform equivalent.
string result =
System.Environment.OSVersion.Platform.ToString();
try
{
SelectQuery querySet =
new SelectQuery("Win32_OperatingSystem");
ManagementObjectSearcher queryScan =
new ManagementObjectSearcher(querySet);
ManagementObjectCollection results = queryScan.Get();
if (results.Count > 0)
{
ManagementObjectCollection.
ManagementObjectEnumerator
resultsEnumerator = results.GetEnumerator();
resultsEnumerator.MoveNext();
result = (string)resultsEnumerator.Current.
Properties["Name"].Value;
if (result.Contains('|') == true)
result = result.Substring(0,
result.IndexOf('|'));
}
} catch { }
OSPlatform Property
♦ My.Computer.Info.OSPlatform
Returns the platform name of the operating system.
VISUAL BASIC
Dim result As String = My.Computer.Info.OSPlatform
C#
string result = System.Environment.
OSVersion.Platform.ToString();
OSVersion Property
♦ My.Computer.Info.OSVersion
Returns the version number of the operating system.
VISUAL BASIC
Dim result As String = My.Computer.Info.OSVersion
C#
string result = System.Environment.
OSVersion.Version.ToString();
PerformanceData Property
♦ My.Computer.Registry.PerformanceData
Returns a reference to the HKEY_PERFORMANCE_DATA Windows registry location.
VISUAL BASIC
Dim result As Microsoft.Win32.RegistryKey =
My.Computer.Registry.PerformanceData
C#
Microsoft.Win32.RegistryKey result =
Microsoft.Win32.Registry.PerformanceData;
Ping Method
♦ My.Computer.Network.Ping
Tests for the presence of another computer or device on a network by issuing an ICMP protocol echo request.
VISUAL BASIC
' ----- Using string host or IP address, default timeout.
Dim result As Boolean = My.Computer.Network.Ping(
"www.example.com")
' ----- Using Uri host, specific timeout.
Dim target As New System.Uri("http://www.example.com")
Dim result As Boolean = My.Computer.Network.Ping(
target, 3000)
C#
// ----- Using string host or IP address, default timeout.
bool result = ((new System.Net.NetworkInformation.Ping())
.Send("www.example.com").Status ==
System.Net.NetworkInformation.IPStatus.Success);
// ----- Using Uri host, specific timeout.
System.Uri target = new System.Uri("http://www.example.com");
bool result = ((new System.Net.NetworkInformation.Ping())
.Send(target.Host, 3000).Status ==
System.Net.NetworkInformation.IPStatus.Success);
Play Method
♦ My.Computer.Audio.Play
Plays a sound contained in a file, byte array, or data stream.
VISUAL BASIC
' ----- Play sound file in background mode.
My.Computer.Audio.Play(soundFile, AudioPlayMode.Background)
C#
// ----- Play sound file in background mode.
System.Media.SoundPlayer audioSource =
new System.Media.SoundPlayer(soundFile);
audioSource.Play();
In addition to specifying a file containing sound content, the Play method accepts a byte array or stream. The SoundPlayer class will work with a data string, or a byte array wrapped in a stream.
C#
// ----- Sound contained in a stream.
System.Media.SoundPlayer audioSource =
new System.Media.SoundPlayer(existingStream);
// ----- Sound contained in a byte array.
System.IO.MemoryStream bytesAsStream =
new System.IO.MemoryStream(existingByteArray);
System.Media.SoundPlayer audioSource =
new System.Media.SoundPlayer(bytesAsStream);
// ----- Later...
bytesAsStream.Close();
The Play method accepts an argument that indicates how to play the sound, whether in the foreground, the background, or looping in the background. When using the SoundPlayer class in C#, call different methods to emulate the related AudioPlayModeenumeration value.
AudioPlayMode Value |
SoundPlayer Method |
Background |
Play |
BackgroundLoop |
PlayLooping |
WaitToComplete |
PlaySync |
PlaySystemSound Method
♦ My.Computer.Audio.PlaySystemSound
Plays a system-defined sound one time.
VISUAL BASIC
Dim whichSound As System.Media.SystemSound =
System.Media.SystemSounds.Beep
My.Computer.Audio.PlaySystemSound(whichSound)
C#
System.Media.SystemSound whichSound =
System.Media.SystemSounds.Beep;
whichSound.Play();
Ports Object
♦ My.Computer.Ports
See
OpenSerialPort Method, SerialPortNames Property
ProductName Property
♦ My.Application.Info.ProductName
Returns the product name as stored in the assembly.
VISUAL BASIC
Dim result As String = My.Application.Info.ProductName
C#
string result;
System.Reflection.Assembly currentAssembly =
System.Reflection.Assembly.GetEntryAssembly();
if (currentAssembly == null) currentAssembly =
System.Reflection.Assembly.GetCallingAssembly();
object[] attrSet = currentAssembly.GetCustomAttributes(
typeof(System.Reflection.AssemblyProductAttribute),
inherit:true);
if (attrSet.Length == 0)
result = "";
else
result = ((System.Reflection.AssemblyProductAttribute)
attrSet[0]).Product;
ProgramFiles Property
♦ My.Computer.FileSystem.SpecialDirectories.ProgramFiles
Returns the path to the native “program files” folder on the local system.
VISUAL BASIC
Dim result As String = My.Computer.FileSystem.
SpecialDirectories.ProgramFiles
C#
string result = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.ProgramFiles);
Programs Property
♦ My.Computer.FileSystem.SpecialDirectories.Programs
Returns the path to the “program groups” folder for the current user.
VISUAL BASIC
Dim result As String = My.Computer.FileSystem.
SpecialDirectories.Programs
C#
string result = System.Environment.GetFolderPath(
System.Environment.SpecialFolder.Programs);
ReadAllBytes Method
♦ My.Computer.FileSystem.ReadAllBytes
Returns a byte array containing a file’s content.
VISUAL BASIC
Dim result As Byte() = My.Computer.FileSystem.ReadAllBytes(
"C:\temp\RawData.dat")
C#
byte[] result = System.IO.File.ReadAllBytes(
"C:\\temp\\RawData.dat");
ReadAllText Method
♦ My.Computer.FileSystem.ReadAllText
Returns a string containing a file’s content.
VISUAL BASIC
Dim optionalEncoding As System.Text.Encoding =
System.Text.UnicodeEncoding
Dim result As String = My.Computer.FileSystem.ReadAllText(
"C:\temp\WorkFile.txt", optionalEncoding)
C#
System.Text.Encoding optionalEncoding =
System.Text.UnicodeEncoding;
string result = System.IO.File.ReadAllText(
"C:\\temp\\WorkFile.txt", optionalEncoding);
The second argument to this method specifies an optional text encoding system. If absent, the text is read using the encoding specified by the file itself, if available.
Registry Object
♦ My.Computer.Registry
See
ClassesRoot Property, CurrentConfig Property, CurrentUser Property, DynData Property, GetValue Method, LocalMachine Property, PerformanceData Property, SetValue Method, Users Property
RenameDirectory Method
♦ My.Computer.FileSystem.RenameDirectory
Renames an existing directory, keeping it in the same original directory.
VISUAL BASIC
My.Computer.FileSystem.RenameDirectory(
"C:\temp\WorkArea", "BackupArea")
C#
System.IO.Directory.Move(
"C:\\temp\\WorkArea", "C:\\temp\\BackupArea");
The RenameDirectory method requires that the new name be just a directory name, with no path or drive information. The C# alternative allows either the source or destination path to be relative or absolute.
RenameFile Method
♦ My.Computer.FileSystem.RenameFile
Renames a file to a new name, keeping it in the same directory.
VISUAL BASIC
My.Computer.FileSystem.RenameFile(
"C:\temp\WorkFile.txt", "BackupWorkFile.old")
C#
System.IO.File.Move("C:\\temp\\WorkFile.txt",
"C:\\temp\\BackupWorkFile.old");
The RenameFile method requires that the new name be just a file name, with no path or drive information. The C# alternative allows either the source or destination path to be relative or absolute.
Request Object
♦ My.Request
Exposes request details for the current ASP.NET HTTP request.
VISUAL BASIC
Dim currentRequest As System.Web.HttpRequest = My.Request
C#
System.Web.HttpRequest currentRequest =
System.Web.HttpContext.Current.Request;
Resources Object
♦ My.Resources
Accesses resources defined through the Project Properties.
VISUAL BASIC
Dim template As String = My.Resources.DisplayTemplate
C#
string template = Properties.Resources.DisplayTemplate;
Response Object
♦ My.Response
Exposes response details for the current ASP.NET HTTP response.
VISUAL BASIC
Dim currentResponse As System.Web.HttpResponse =
My.Response
C#
System.Web.HttpResponse currentResponse =
System.Web.HttpContext.Current.Response;
Run Method
♦ My.Application.Run
Starts a Windows application using the Windows Forms Application Framework.
VISUAL BASIC
My.Application.Run(commandLineArgs)
The Run method is only available in VB programs that employ the Windows Forms Application Framework. The Application class in the System.Windows.Forms namespace also exposes a Run method. It provides similar functionality, but accepts a Form instance or an ApplicationContext instance instead of an array of command-line arguments. In C#, you can call the Environment.GetCommandLineArgs method to retrieve this information.
C#
// ----- Run the application focused on the
// main form instance.
Application.Run(new MainForm());
SaveMySettingsOnExit Property
♦ My.Application.SaveMySettingsOnExit
Indicates whether the settings should be saved when exiting the application.
VISUAL BASIC
Dim result As Boolean = My.Application.SaveMySettingsOnExit
C# does not include an equivalent for Visual Basic’s SaveMySettingsOnExit property. Instead, settings must be saved manually on exit. The following code saves any updated settings.
C#
Properties.Settings.Default.Save();
See Also
Settings Object
Screen Property
♦ My.Computer.Screen
Returns an object containing information and settings about the primary display.
VISUAL BASIC
Dim result As System.Windows.Forms.Screen =
My.Computer.Screen
C#
// ----- For Windows Forms code:
System.Windows.Forms.Screen result =
System.Windows.Forms.Screen.PrimaryScreen;
In XAML-centric code, the System.Windows.SystemParameters class exposes several static properties that provide screen-related information.
ScrollLock Property
♦ My.Computer.Keyboard.ScrollLock
Indicates whether the Scroll Lock key is currently activated.
VISUAL BASIC
Dim result As Boolean = My.Computer.Keyboard.ScrollLock
C#
// ----- For Windows Forms code:
bool result = System.Windows.Forms.Form.IsKeyLocked(
System.Windows.Forms.Keys.Scroll);
// ----- For XAML-centric code:
bool result = System.Windows.Input.Keyboard.IsKeyToggled(
System.Windows.Input.Key.Scroll);
SendKeys Method
♦ My.Computer.Keyboard.SendKeys
Sends keystrokes to the active window as if typed from the keyboard.
VISUAL BASIC
' ----- Send Control-C "copy" sequence to the
' active window.
Dim waitForProcessing As Boolean = True
My.Computer.Keyboard.SendKeys("^c", waitForProcessing)
C#
// ----- Send Control-C "copy" sequence to the
// active window.
System.Windows.Forms.SendKeys.SendWait("^c");
// ----- To return without waiting.
System.Windows.Forms.SendKeys.Send("^c");
XAML-based applications typically do not have access to the SendKeys class. Instead, such programs must call the SendInput Win32 API. Use of this API is beyond the scope of this chapter. Access the “SendInput Function” entry on Microsoft’s MSDN web site for information on calling this API.
The SendKeys command uses a set of specially formatted codes, such as {BACKSPACE}, to send non-standard characters and sequences to the target window. See the Visual Studio documentation for the full set of codes.
SerialPortNames Property
♦ My.Computer.Ports.SerialPortNames
Returns a collection of serial port names found on the local computer.
VISUAL BASIC
' ----- This code returns a read-only collection of
' the serial port names.
Dim result As System.Collections.Generic.
ReadOnlyCollection(Of String) =
My.Computer.Ports.SerialPortNames
C#
// ----- This code returns an ordinary string array of
// the serial port names.
string[] result =
System.IO.Ports.SerialPort.GetPortNames();
SetAudio Method
♦ My.Computer.Clipboard.SetAudio
Writes audio data to the system clipboard. The audio content supplied can be in the form of a byte array or a stream (System.IO.Stream).
VISUAL BASIC
' Option 1: Dim audioContent() As Byte
' Option 2: Dim audioContent As System.IO.Stream
My.Computer.Clipboard.SetAudio(audioContent)
C#
// Option 1: byte[] audioContent;
// Option 2: System.IO.Stream audioContent;
// ----- For Windows Forms code:
System.Windows.Forms.Clipboard.SetAudio(audioContent);
// ----- For XAML-centric code:
System.Windows.Clipboard.SetAudio(audioContent);
SetData Method
♦ My.Computer.Clipboard.SetData
Writes data in a custom named format to the system clipboard.
VISUAL BASIC
Dim formatName As String = "MyCustomFormat"
Dim customData As Object ' Assign any data you choose
My.Computer.Clipboard.SetData(formatName, customData)
C#
string formatName = "MyCustomFormat";
object customData; // Assign any data you choose
// ----- For Windows Forms code:
System.Windows.Forms.Clipboard.SetData(
formatName, customData);
// ----- For XAML-centric code:
System.Windows.Clipboard.SetData(
formatName, customData);
SetDataObject Method
♦ My.Computer.Clipboard.SetDataObject
Writes data to the system clipboard in multiple formats at once.
VISUAL BASIC
Dim toClipboard As New System.Windows.Forms.DataObject
toClipboard.SetText("Some basic text.")
toClipboard.SetData("Backwards", ".txet cisab emoS")
My.Computer.Clipboard.SetDataObject(toClipboard)
C#
// ----- For Windows Forms code:
System.Windows.Forms.DataObject toClipboard =
new System.Windows.Forms.DataObject();
toClipboard.SetText("Some basic text.");
toClipboard.SetData("Backwards", ".txet cisab emoS");
System.Windows.Forms.Clipboard.SetDataObject(toClipboard);
// ----- For XAML-centric code:
System.Windows.DataObject toClipboard =
new System.Windows.DataObject();
toClipboard.SetText("Some basic text.");
toClipboard.SetData("Backwards", ".txet cisab emoS");
System.Windows.Clipboard.SetDataObject(toClipboard);
SetFileDropList Method
♦ My.Computer.Clipboard.SetFileDropList
Writes a collection of file-path strings to the system clipboard.
VISUAL BASIC
Dim files As New _
System.Collections.Specialized.StringCollection
files.Add("C:\temp\FileToShare.txt")
My.Computer.Clipboard.SetFileDropList(files)
C#
System.Collections.Specialized.StringCollection files =
new System.Collections.Specialized.StringCollection();
files.Add("C:\\temp\\FileToShare.txt");
// ----- For Windows Forms code:
System.Windows.Forms.Clipboard.SetFileDropList(files);
// ----- For XAML-centric code:
System.Windows.Clipboard.SetFileDropList(files);
SetImage Method
♦ My.Computer.Clipboard.SetImage
Writes an image to the system clipboard.
VISUAL BASIC
Dim someImage As System.Drawing.Image
' ----- After loading the image.
My.Computer.Clipboard.SetImage(someImage)
C#
// ----- For Windows Forms code:
System.Drawing.Image someImage;
System.Windows.Forms.Clipboard.SetImage(someImage);
// ----- For XAML-centric code:
System.Windows.Media.Imaging.BitmapSource someImage;
System.Windows.Clipboard.SetImage(someImage);
SetText Method
♦ My.Computer.Clipboard.SetText
Writes a text string to the system clipboard.
VISUAL BASIC
My.Computer.Clipboard.SetText("Hello, world!")
C#
// ----- For Windows Forms code:
System.Windows.Forms.Clipboard.SetText("Hello, world!");
// ----- For XAML-centric code:
System.Windows.Clipboard.SetText("Hello, world!");
The SetText method accepts a second optional argument that indicates the type of text to store, such as HTML or Unicode. In the My and Windows Forms versions of the code, this argument is of type System.Windows.Forms.TextDataFormat; for XAML code, use the System.Windows.TextDataFormat enumeration instead. By default, the text is stored in Unicode format.
Settings Object
♦ My.Settings
Accesses user and application settings defined through the Project Properties.
VISUAL BASIC
' ----- Accessing a setting.
Dim result As Point = My.Settings.DisplayLocation
' ----- Modifying a setting (user-scope only).
My.Settings.DisplayLocation = targetForm.Location
' ----- Saving all settings.
My.Settings.Save()
C#
// ----- Accessing a setting.
Point result = Properties.Settings.Default.DisplayLocation;
// ----- Modifying a setting (user-scope only).
Properties.Settings.Default.DisplayLocation =
targetForm.Location;
// ----- Saving all settings.
Properties.Settings.Default.Save();
SetValue Method
♦ My.Computer.Registry.SetValue
Saves data into a specified Windows registry value.
VISUAL BASIC
My.Computer.Registry.SetValue(
"HKEY_CURRENT_USER\Software\Example\MyApp",
"ErrorCount", 0&, RegistryValueKind.QWord))
C#
Microsoft.Win32.Registry.SetValue(
"HKEY_CURRENT_USER\\Software\\Example\\MyApp",
"ErrorCount", 0L, RegistryValueKind.QWord);
ShiftKeyDown Property
♦ My.Computer.Keyboard.ShiftKeyDown
Indicates whether a Shift key is currently pressed.
VISUAL BASIC
Dim result As Boolean = My.Computer.Keyboard.ShiftKeyDown
C#
// ----- For Windows Forms code:
bool result = ((System.Windows.Forms.Control.ModifierKeys &
System.Windows.Forms.Keys.Shift) != 0);
// ----- For XAML-centric code:
bool result = ((System.Windows.Input.Keyboard.Modifiers &
System.Windows.Input.ModifierKeys.Shift) != 0);
Shutdown Event
♦ My.Application.Shutdown
Occurs when the application shuts down.
VISUAL BASIC
Public Sub Me_Shutdown(ByVal sender As Object,
ByVal e As EventArgs) Handles Me.Shutdown
' ----- Relevant shutdown code here.
End Sub
The Shutdown event is only available in VB programs that employ the Windows Forms Application Framework. However, you can perform shutdown-related processing in any application by adding a handler to the ProcessExit event for the current application domain.
C#
static void ShutdownLogic(object sender, EventArgs e)
{
// ----- Relevant shutdown code here.
}
// ----- In your Main routine, before running the core
// program logic.
AppDomain.CurrentDomain.ProcessExit += ShutdownLogic;
The application context object for an application exposes a similar event that you can use instead of ProcessExit to monitor the application’s main thread.
C#
// ----- In your Main routine.
ApplicationContext appContext = new ApplicationContext();
appContext.ThreadExit += ShutdownLogic;
appContext.MainForm = new Form1();
Application.Run(appContext);
SpecialDirectories Object
♦ My.Computer.FileSystem.SpecialDirectories
See
AllUsersApplicationData Property, CurrentUserApplicationData Property, Desktop Property, MyDocuments Property, MyMusic Property, MyPictures Property, Programs Property, Temp Property
SplashScreen Property
♦ My.Application.SplashScreen
Identifies the form used as the splash screen in a Windows Forms application.
VISUAL BASIC
My.Application.SplashScreen = New SplashForm
Visual Basic includes features that let you display a splash screen with some basic logic. In C#, any splash screen must be displayed manually through custom code. The following method can be called from the Main method to display a splash screen.
C#
// ----- Call this routine from Main.
private static void ShowSplashScreen()
{
// ----- Show the splash screen on its own thread.
System.Threading.Thread splashThread =
new System.Threading.Thread(DisplaySplash);
splashThread.Start();
}
private static void DisplaySplash()
{
// ----- Assume a form with an exposed timer that
// will close the form after some time.
Application.Run(new SplashForm());
}
StackTrace Property
♦ My.Application.Info.StackTrace
Returns a string version of the current stack trace.
VISUAL BASIC
Dim result As String = My.Application.Info.StackTrace
C#
string result = System.Environment.StackTrace;
Startup Event
♦ My.Application.Startup
Triggered when starting a Windows Forms application that uses VB’s Windows Forms Application Framework.
VISUAL BASIC
Public Sub Me_Startup(ByVal sender As Object,
ByVal e As StartupEventArgs) Handles Me.Startup
' ----- Custom startup code here. To abort...
e.Cancel = True
End Sub
C# does not include an equivalent to VB’s Windows Forms Application Framework. However, because all C# programs begin with a Main method, you can place relevant custom code directly in that method.
C#
public static void Main()
{
// ----- Custom code here. To abort...
Application.Exit();
}
StartupNextInstance Event
♦ My.Application.StartupNextInstance
Called when a subsequent instance of a single-instance Windows Forms application starts up. The event occurs in the primary instance.
VISUAL BASIC
Public Sub Me_StartupNextInstance(ByVal sender As Object,
ByVal e As StartupNextInstanceEventArgs) _
Handles Me.StartupNextInstance
' ----- Instance-handling code here.
End Sub
The StartupNextInstance event is only available in VB programs that employ the Windows Forms Application Framework. In C#, you must monitor the startup of subsequent instances manually. The following Main method provides an example of how you can watch for subsequent instances using a shared mutex object.
C#
// ----- Assumes: using System.Threading;
public static void Main()
{
System.Version versionInfo;
string mutexName;
Mutex appMutex = null;
bool firstInstance = false;
// ----- Provide a reasonably unique mutex name.
// GUIDs will also work.
versionInfo = System.Reflection.Assembly.
GetExecutingAssembly().GetName().Version;
mutexName = string.Format(
"VendorName/AppName({0}.{1})",
versionInfo.Major, versionInfo.Minor);
try
{
// ----- See if another instance exists.
appMutex = Mutex.OpenExisting(mutexName);
}
catch
{
// ----- Not found or other failure.
// Try to create one.
try
{
appMutex = new Mutex(true, mutexName,
out firstInstance);
}
catch
{
firstInstance = false;
}
}
if (firstInstance)
{
// ----- Continue with application logic.
}
else
{
// ----- This is a subsequent instance.
}
// ----- When finished with the app, clean up.
if (appMutex != null)
appMutex.Close();
}
Visual Basic’s StartupNextInstance shuts down the subsequent instance and passes any of its command-line arguments to the first instance through the event’s e argument. It does this through interprocess communications, a demonstration of which is beyond the scope of this entry.
Stop Method
♦ My.Computer.Audio.Stop
Stops a sound that is currently playing.
VISUAL BASIC
' ----- Play sound file in background mode.
My.Computer.Audio.Play(soundFile, AudioPlayMode.Background)
' ----- Later, stop the sound.
My.Computer.Audio.Stop()
C#
// ----- Play sound file in background mode.
System.Media.SoundPlayer audioSource =
new System.Media.SoundPlayer(soundFile);
audioSource.Play();
// ----- Later, stop the sound.
audioSource.Stop();
Temp Property
♦ My.Computer.FileSystem.SpecialDirectories.Temp
Returns the path to the temporary-file folder for the current user.
VISUAL BASIC
Dim result As String = My.Computer.FileSystem.
SpecialDirectories.Temp
C#
string result = System.IO.Path.GetTempPath();
TextFieldParser Object
See
OpenTextFieldParser Method
TickCount Property
♦ My.Computer.Clock.TickCount
Returns the number of milliseconds elapsed since system startup, or since the last time the counter reset, about once every 25 days.
VISUAL BASIC
Dim result As Integer = My.Computer.Clock.TickCount
C#
int result = System.Environment.TickCount;
Title Property
♦ My.Application.Info.Title
Returns the application title as stored in the assembly.
VISUAL BASIC
Dim result As String = My.Application.Info.Title
C#
string result;
System.Reflection.Assembly currentAssembly =
System.Reflection.Assembly.GetEntryAssembly();
if (currentAssembly == null) currentAssembly =
System.Reflection.Assembly.GetCallingAssembly();
object[] attrSet = currentAssembly.GetCustomAttributes(
typeof(System.Reflection.AssemblyTitleAttribute),
inherit:true);
if (attrSet.Length == 0)
result = "";
else
result = ((System.Reflection.AssemblyTitleAttribute)
attrSet[0]).Title;
TotalPhysicalMemory Property
♦ My.Computer.Info.TotalPhysicalMemory
Returns the total number of installed bytes of physical memory on the local computer.
VISUAL BASIC
Dim result As ULong = My.Computer.Info.TotalPhysicalMemory
C#
// ----- GetMemoryInfo code discussed below.
ulong result = MemoryQuery.GetMemoryInfo().TotalPhysical;
Visual Basic retrieves memory information through the GlobalMemoryStatusEx Windows API call. See the “AvailablePhysicalMemory Property” entry in this chapter for a sample GetMemoryInfo method that wraps the API call in C# code.
TotalVirtualMemory Property
♦ My.Computer.Info.TotalVirtualMemory
Returns the total number of configured bytes of virtual memory on the local computer.
VISUAL BASIC
Dim result As ULong = My.Computer.Info.TotalVirtualMemory
C#
// ----- GetMemoryInfo code discussed below.
ulong result = MemoryQuery.GetMemoryInfo().TotalVirtual;
Visual Basic retrieves memory information through the GlobalMemoryStatusEx Windows API call. See the “AvailablePhysicalMemory Property” entry in this chapter for a sample GetMemoryInfo method that wraps the API call in C# code.
TraceSource Property
♦ My.Application.Log.TraceSource (for Desktop applications)
♦ My.Log.TraceSource (for ASP.NET applications)
Unlike with Visual Basic, C# does not configure a built-in logging environment by default. Instead, you can add a Logging Application Block from the Microsoft Enterprise Library to your application. The code needed to set up and use trace logging in your application is beyond the scope of this book.
You can find full information on the Logging Application Block, including sample code, on the MSDN web site, msdn.microsoft.com. On that site, search for “Enterprise Library 6.” The first result should be a link to the Developer’s Guide for the Microsoft Enterprise Library. Chapter 5, “As Easy As Falling Off a Log,” provides an overview of the logging components.
Visual Basic’s logging tools include WriteEntry and WriteException methods. In the sample code for the Logging Application Block, the LogWriter.Write method provides a good substitute for VB’s own WriteEntry method. However, the Enterprise Library does not include a write method designed for Exception instances. Instead, you must format the exception message yourself, and then pass it to the LogWriter.Write method.
Trademark Property
♦ My.Application.Info.Trademark
Returns the legal trademark as stored in the assembly.
VISUAL BASIC
Dim result As String = My.Application.Info.Trademark
C#
string result;
System.Reflection.Assembly currentAssembly =
System.Reflection.Assembly.GetEntryAssembly();
if (currentAssembly == null) currentAssembly =
System.Reflection.Assembly.GetCallingAssembly();
object[] attrSet = currentAssembly.GetCustomAttributes(
typeof(System.Reflection.AssemblyTrademarkAttribute),
inherit:true);
if (attrSet.Length == 0)
result = "";
else
result = ((System.Reflection.
AssemblyTrademarkAttribute)
attrSet[0]).Trademark;
UICulture Property
♦ My.Application.UICulture
Returns an object that describes the user interface culture.
VISUAL BASIC
Dim result As System.Globalization.CultureInfo =
My.Application.UICulture
C#
System.Globalization.CultureInfo result =
System.Threading.Thread.CurrentThread.CurrentUICulture;
UnhandledException Event
♦ My.Application.UnhandledException
Catches unhandled exceptions within a Windows Forms application that uses VB’s Windows Forms Application Framework.
VISUAL BASIC
Public Sub Me_UnhandledException(ByVal sender As Object,
ByVal e As UnhandledExceptionEventArgs) _
Handles Me.UnhandledException
' ----- Relevant error-handling code here.
End Sub
The UnhandledException event is only available in VB programs that employ the Windows Forms Application Framework. However, you can manage unhandled exceptions in any application by adding a handler to the UnhandledException event for the current application domain.
C#
static void SurpriseProblem(object sender,
UnhandledExceptionEventArgs e)
{
// ----- Relevant error-handling code here.
}
// ----- In your Main routine, before running the core
// program logic.
AppDomain.CurrentDomain.UnhandledException +=
SurpriseProblem;
You can also add a thread-specific handler that monitors unhandled exceptions in your main (UI) thread.
C#
static void ThreadProblem(object sender,
System.Threading.ThreadExceptionEventArgs e)
{
// ----- Relevant error-handling code here.
}
// ----- In your Main routine, before running the core
// program logic.
Application.ThreadException += ThreadProblem;
UploadFile Method
♦ My.Computer.Network.UploadFile
Uploads a file from a local computer to a network address.
VISUAL BASIC
My.Computer.Network.UploadFile(sourceFile,
destinationAddress, userName, password)
C#
System.Net.WebClient client = new System.Net.WebClient();
System.Uri destinationUri =
new System.Uri(destinationAddress);
// ----- Default credentials.
client.UseDefaultCredentials = true;
// ----- Or, supply specific credentials.
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential(
userName, password);
// ----- Synchronous copy.
client.UploadFile(destinationUri, sourceFile);
// ----- Or, asynchronous copy, providing your own
// custom complete/cancel event handler.
client.UploadFileCompleted += new
UploadFileCompletedEventHandler(CompletedCallback);
client.UploadFileAsync(destinationUri, sourceFile);
The WebClient class’ upload methods provide no visual cues as to the state of the transfer. You must provide your own progress dialog if desired.
To override the default timeout value, derive a new class from the WebClient class, and manually configure the WebRequest’s TimeOut property. Then use this class instead of the standard WebClient class to perform the upload. For a sample of this override in C#, see the “DownloadFile Method” entry in this chapter.
See Also
DownloadFile Method
User Object
♦ My.User
See
CurrentPrincipal Property, InitializeWithWindowsUser Method, IsAuthenticated Property, IsInRole Method, Name Property (My.User)
Users Property
♦ My.Computer.Registry.Users
Returns a reference to the HKEY_USERS Windows registry location.
VISUAL BASIC
Dim result As Microsoft.Win32.RegistryKey =
My.Computer.Registry.Users
C#
Microsoft.Win32.RegistryKey result =
Microsoft.Win32.Registry.Users;
Version Property
♦ My.Application.Info.Version
Returns the version numbers of the application as stored in the assembly.
VISUAL BASIC
Dim result As System.Version = My.Application.Info.Version
C#
System.Reflection.Assembly currentAssembly =
System.Reflection.Assembly.GetEntryAssembly();
if (currentAssembly == null) currentAssembly =
System.Reflection.Assembly.GetCallingAssembly();
System.Version result = currentAssembly.GetName().Version;
WebServices Object
♦ My.WebServices
Accesses web services and their members from a non-ASP.NET application.
VISUAL BASIC
' ----- Assumes a MappingService web service with a
' GetNearestCity member is part of the project.
Dim result As String =
My.WebServices.MappingService.GetNearestCity(
targetLatitude, targetLongitude)
C#
// ----- Assumes a MappingService web service with a
// GetNearestCity member is part of the project.
MappingNamespace.MappingService theService =
new MappingNamespace.MappingService();
string result = theService.GetNearestCity(
targetLatitude, targetLongitude);
WheelExists Property
♦ My.Computer.Mouse.WheelExists
Returns a value that indicates whether the installed mouse includes a mouse wheel.
VISUAL BASIC
Dim result As Boolean = My.Computer.Mouse.WheelExists
C#
// ----- For Windows Forms code:
bool result = System.Windows.Forms.SystemInformation.
MouseWheelPresent;
// ----- For XAML-centric code:
bool result = System.Windows.SystemParameters.
IsMouseWheelPresent;
WheelScrollLines Property
♦ My.Computer.Mouse.WheelScrollLines
Returns the number of lines to scroll during mouse wheel operations.
VISUAL BASIC
Dim result As Integer = My.Computer.Mouse.WheelScrollLines
C#
// ----- For Windows Forms code:
int result = System.Windows.Forms.SystemInformation.
MouseWheelScrollLines;
// ----- For XAML-centric code:
int result =
System.Windows.SystemParameters.WheelScrollLines;
WorkingSet Property
♦ My.Application.Info.WorkingSet
Returns the size in bytes of physical memory mapped to the current process context.
VISUAL BASIC
Dim result As Long = My.Application.Info.WorkingSet
C#
long result = System.Environment.WorkingSet;
WriteAllBytes Method
♦ My.Computer.FileSystem.WriteAllBytes
Writes the content of a byte array to a specified file.
VISUAL BASIC
Dim whichFile As String = "C:\temp\SomeData.dat"
Dim theData() As Byte = GetMyByteData()
Dim append As Boolean = False
My.Computer.FileSystem.WriteAllBytes(
whichFile, theData, append)
C#
string whichFile = "C:\\temp\\SomeData.dat";
byte[] theData = GetMyByteData();
bool append = false;
System.IO.FileStream outFile;
System.IO.FileMode outMethod;
if (append)
outMethod = System.IO.FileMode.Append;
else
outMethod = System.IO.FileMode.Create;
outFile = new System.IO.FileStream(whichFile, outMethod,
System.IO.FileAccess.Write, System.IO.FileShare.Read);
outFile.Write(theData, 0, theData.Length);
outFile.Close();
WriteAllText Method
♦ My.Computer.FileSystem.WriteAllText
Writes text content to a specified file.
VISUAL BASIC
Dim filePath As String = "C:\temp\Output.txt"
Dim content As String = "Hello, world!" + vbCrLf
Dim appendFlag As Boolean = False
Dim optionalEncoding As System.Text.Encoding =
New System.Text.UTF8Encoding
My.Computer.FileSystem.WriteAllText(
filePath, content, appendFlag, optionalEncoding)
C#
string filePath = "C:\\temp\\Output.txt";
string content = "Hello, world!\r\n";
System.Text.Encoding optionalEncoding =
new System.Text.UTF8Encoding();
// ----- To create or overwrite a file:
System.IO.File.WriteAllText(
filePath, content, optionalEncoding);
// ----- To append to an existing file:
System.IO.File.AppendAllText(
filePath, content, optionalEncoding);
WriteEntry Method
♦ My.Application.Log.WriteEntry (for Desktop applications)
♦ My.Log.WriteEntry (for ASP.NET applications)
Writes a message to the logging system.
See
TraceSource Property
WriteException Method
♦ My.Application.Log.WriteException (for Desktop applications)
♦ My.Log.WriteException (for ASP.NET applications)
Writes an exception to the logging system.
See
TraceSource Property