Archive for the 'Microsoft' Category



C# How to: Changing a File’s read only attribute

When working on certain types of projects you might find a commonly used/repeated task being able to determine and manipulate a file’s read only attribute. This article provides a discussion on how to determine whether a file is read only or not, provides three different methods of setting a file to read only and provides three different methods of negating a file’s read only status.

The topics discussed in this article is focussed around a Console based sample application. You can download the complete Visual Studio project source code here.

How to determine if a file is read only or not

The System.IO.FileInfo class exposes the Boolean property IsReadOnly. It is important to note that the FileInfo.IsReadOnly property reflects a file’s read only status at the point in time when the FileInfo object was instantiated or the last time the FileInfo.Refresh() method was invoked. The ReadOnly property reflects a snapshot of a file’s read only status. If a file’s read only attribute is manipulated after FileInfo object instantiation or after invoking the Refresh() method the ReadOnly property will not reflect any changes that may have occurred subsequently. It is therefore good practice to invoke FileInfo.Refresh() before accessing the ReadOnly property in order to safeguard against file attribute changes your application may be unaware of.

 private static void DisplayFileStatus(FileInfo fileInfo)
 {
     fileInfo.Refresh();
 
     Console.WriteLine("File read only: " +
         (fileInfo.IsReadOnly ? "Yes" : "No" ));
 }

The sample code provided with this article implements the DisplayFileStatus method as an easily reusable method of determining a file’s read only status and displaying the result to the Console.

Creating a new file

 Console.WriteLine("Creating new file...");
 StreamWriter streamWriter = File.CreateText("ReadOnlyFile.txt");
 streamWriter.WriteLine("This is a code sample from http://softwarebydefault.com");
 streamWriter.Close();
 Console.WriteLine("File Created.");
 
 FileInfo fileInfo = new FileInfo("ReadOnlyFile.txt");
 DisplayFileStatus(fileInfo);
 Console.WriteLine();

The code snippet listed above creates a new file called “ReadOnlyFile.txt” by implementing the File.CreateText(string) method. The CreateText() method returns an object of type StreamWriter, which is then used to write a text string to the newly created file, after which the open file handle is released by invoking StreamWriter.Close().

Furthermore the code snippet illustrates instantiating an object of type FileInfo, which is specified to reference the previously newly created file. The file’s read only attribute gets output to the Console by invoking the DisplayFileStatus() method discussed earlier.

Setting a file to read only – Method 1

 Console.WriteLine("Attempting to set read only: method 1");
 fileInfo.IsReadOnly = true;
 DisplayFileStatus(fileInfo);
 Console.WriteLine();

This method simply sets the property FileInfo.IsReadOnly to true and then determines and output the file’s read only attribute.

Setting a file to read only – Method 2

 Console.WriteLine("Attempting to set read only: method 2");
 File.SetAttributes("ReadOnlyFile.txt", FileAttributes.ReadOnly);
 DisplayFileStatus(fileInfo);
 Console.WriteLine();

Method 2 invokes the File class’ SetAttributes method, passing as parameters the name of the file created earlier and the enumeration value FileAttributes.ReadOnly.

Setting a file to read only – Method 3

 Console.WriteLine("Attempting to set read only: method 3");
 fileInfo.Attributes = fileInfo.Attributes | FileAttributes.ReadOnly;
 DisplayFileStatus(fileInfo);
 Console.WriteLine();

The third method, shown in the code snippet above, updates the value of the FileInfo class’ FileInfo.Attributes property, which is an enumeration of type System.IO.FileAttributes. The FileAttributes enumeration as part of its declaration implements [FlagsAttribute].

When an enumeration’s declaration includes the attribute FlagsAttribute, it is an indication that the enumeration is to be used as a bit field, also commonly referred to as flags. When regarding the FileInfo.Attributes property as a bit field it logically follows that bitwise operations can be performed.

The code snippet performs a bitwise OR operation specifying the enumeration value FileAttributes.ReadOnly. If the FileInfo.Attributes bit field property is already set to include FileAttributes.ReadOnly, performing a bitwise OR operation will have no effect. Inversely, if  FileInfo.Attributes is not set to include FileAttributes.ReadOnly, the bitwise OR operation will set the flag to true. 

Removing a file’s read only attribute – Method 1

 Console.WriteLine("Attempting to undo read only: method 1");
 fileInfo.IsReadOnly = false;
 DisplayFileStatus(fileInfo);
 Console.WriteLine();

The first method shown to remove a file’s read only attribute functions by achieving the exact opposite of the first method shown in setting a file to read only. Updating the value of the FileInfo.IsReadOnly Boolean property to false results in the referenced file no longer being read only.

Removing a file’s read only attribute – Method 2

 Console.WriteLine("Attempting to undo read only method 2");
 File.SetAttributes("ReadOnlyFile.txt", ~FileAttributes.ReadOnly);
 DisplayFileStatus(fileInfo);
 Console.WriteLine();

The code snippet above illustrates the second method of updating a file to not include the read only attribute. In a similar fashion to the first method described the second method implements the code required to achieve an effect opposite to that of the second method of setting a file to read only. By making use of the ~ operator a bitwise compliment operation is performed on FileAttributes.ReadOnly, the result of which is passed as a parameter to the File.SetAttributes method. An alternative explanation could be stated as reversing the bit values represented by the enumeration member FileAttributes.ReadOnly before applying the reversed bit values as a parameter to the File.SetAttributes method.

Removing a file’s read only attribute – Method 3

 Console.WriteLine("Attempting to undo read only: method 3");
 fileInfo.Attributes = fileInfo.Attributes & ~FileAttributes.ReadOnly;
 DisplayFileStatus(fileInfo);
 Console.WriteLine();

The third method, as listed above, updates FileInfo.Attributes, which is an enumeration property of type System.IO.FileAttributes, but also a bit field as discussed earlier. Based on the rules of operator precedence the bitwise compliment (~ operator) will be evaluated first, thereafter the bitwise AND operation will be executed. Reversing the bit values of FileAttributes.ReadOnly then applying the resulting values as an operand to a bitwise AND operation results in removing FileAttributes.ReadOnly as a flag set on the FileInfo.Attributes property.

Complete Sample Code

The code listing below represents the entire code sample. You can also download the complete Visual Studio project source code here.

 /*
  * The Following Code was developed by Dewald Esterhuizen
  * View Documentation at: http://softwarebydefault.com
  * Licensed under Ms-PL 
 */
 using  System;
 using  System.Collections.Generic;
 using  System.Linq;
 using  System.Text;
 using  System.IO;
 
 namespace ReadOnlyFiles
 {
     class Program
     {
         static void Main(string [] args)
         {
             Console.WriteLine("Creating new file...");
             StreamWriter streamWriter = File.CreateText("ReadOnlyFile.txt");
             streamWriter.WriteLine("This is a code sample from http://softwarebydefault.com");
             streamWriter.Close();
             Console.WriteLine("File Created.");
 
             FileInfo fileInfo = new FileInfo("ReadOnlyFile.txt");
             DisplayFileStatus(fileInfo);
             Console.WriteLine();
 
             Console.WriteLine("Attempting to set read only: method 1");
             fileInfo.IsReadOnly = true;
             DisplayFileStatus(fileInfo);
             Console.WriteLine();
 
             Console.WriteLine("Attempting to undo read only: method 1");
             fileInfo.IsReadOnly = false;
             DisplayFileStatus(fileInfo);
             Console.WriteLine();
 
             Console.WriteLine("Attempting to set read only: method 2");
             File.SetAttributes("ReadOnlyFile.txt", FileAttributes.ReadOnly);
             DisplayFileStatus(fileInfo);
             Console.WriteLine();
 
             Console.WriteLine("Attempting to undo read only method 2");
             File.SetAttributes("ReadOnlyFile.txt", ~FileAttributes.ReadOnly);
             DisplayFileStatus(fileInfo);
             Console.WriteLine();
 
             Console.WriteLine("Attempting to set read only: method 3");
             fileInfo.Attributes = fileInfo.Attributes | FileAttributes.ReadOnly;
             DisplayFileStatus(fileInfo);
             Console.WriteLine();
 
             Console.WriteLine("Attempting to undo read only: method 3");
             fileInfo.Attributes = fileInfo.Attributes & ~FileAttributes.ReadOnly;
             DisplayFileStatus(fileInfo);
             Console.WriteLine();
 
             Console.WriteLine("Press any key...");
             Console.ReadKey();
 
             File.Delete("ReadOnlyFile.txt");
         }
 
         private static void DisplayFileStatus(FileInfo fileInfo)
         {
             fileInfo.Refresh();
 
             Console.WriteLine("File read only: "+
                 (fileInfo.IsReadOnly ? "Yes" : "No"));
         }
     }
 }
[tweetmeme source=”DefaultSoftware” only_single=”false”]

C# How to: Drawing in GDI with Opacity/Alpha components

Article Purpose

In this article we explore GDI+ drawing operations implementing opacity, also known as alpha blending.

Sample source code

This article is accompanied by a sample source code Visual Studio project which is available for download here

C# How to: Drawing in GDI with Opacity/Alpha components

Using the Sample Application

The following is a screenshot of the included sample application:

GDIOpacityDrawing

The screenshot illustrates drawing text and a rectangle onto a Windows Form in Color.SteelBlue with an alpha component of 100.

GDI+ Drawing

In C# it is possible and relatively easy to draw text and two dimensional shapes in GDI+ that support a level of opacity or transparency. The well known abbreviation RGB abbreviates the term Red, Green and Blue. C# supports RGB colours but also what is known as ARGB colours. In the case of ARGB the A abbreviates the word Alpha, in other words an RGB colour with a specified alpha component.

An alpha component specifies a colour’s opacity or transparency. Possible values range from 0 to 255 inclusive, where 0 would represent full transparency and 255 no level of transparency. If a consists of 8 bits and an ARGB colour is composed of 4 components ranging from 0 to 255 each representing a or 8 bits, then an ARGB colour is therefore a 32 bit colour.

The Color structure

The System.Drawing namespace defines the Color structure, which exposes several functions aimed at creating an ARGB Color object instance:

The Paint Event Handler

The bulk of this example’s functionality occurs within the main Form’s handler, as detailed by the following code snippet:

private void MainFormPaintEventHandler(object sender, PaintEventArgs e) 
{ 
    Color alphaForeColor = Color.FromArgb(this.foreColorAlphaValue, this.ForeColor); 
    Pen rectanglePen = new Pen(alphaForeColor, 2.0f); 
    SolidBrush textBrush = new SolidBrush(alphaForeColor); 

float x = this.ClientRectangle.Width / 2.0f; x -= e.Graphics.MeasureString(textToDisplay, this .Font).Width / 2.0f;
float y = this.ClientRectangle.Height / 2.0f; y -= e.Graphics.MeasureString(textToDisplay, this.Font).Height / 2.0f;
e.Graphics.DrawString(textToDisplay, this.Font, textBrush, new PointF(x, y));
e.Graphics.DrawRectangle(rectanglePen, 25, 25, this.ClientRectangle.Width - 50, this.ClientRectangle.Height - 50); }

The main Form defines two member variables used in the handler:

 private byte foreColorAlphaValue = 100;
 textToDisplay = "http://softwarebydefault.com";

In the handler an instance of the structure is created implementing an alpha component defined by the ’s member variable. The object declaration is followed by an ARGB   Pen and SolidBrush declaration.

Next the code determines the X and Y coordinates that would result in drawing the ’s string member variable in the middle of the , after which the actual drawing occurs.

Using the Pen object declared earlier a rectangle is drawn 25 pixels inside the ’s ClientRectangle.

Shutdown Windows without installing updates

Yesterday I shutdown my notebook  as I was about to leave work. Surprise! There was a couple of hundred Windows updates waiting to be installed. Yes, I’m talking about the dreaded “Install updates and shutdown”, which can take anywhere from a couple of seconds to hours.

I have no problem with installing Windows updates, I think keeping up to date with security updates and bug fixes are important. The problem I do have is in having to wait, especially after a day at the office, having the expectation of freedom shattered by painfully watching updates installing one by one.

If you don’t have time to wait for updates to install and you simply want to shut down, there is a way out. Close your desktop. When viewing your desktop enter alt+F4, which is the general close program command. In the case of the desktop you will be presented with an options menu. One of the options being “Shut Down”, allowing you to bypass “Install updates and shut down”.

Updates

Testing Windows Live Writer Plugins

I recently installed Microsoft Windows Live Writer in order to enable offline/desktop content creation for my blog hosted at WordPress.com So far Live Writer has exceeded my expectations by far, simply put, it is awesome. The user interface is very similar to the familiar Microsoft Office product suite user interface.

Windows Live Writer Screenshot

From Wikipedia: “It features WYSIWYG authoring, photo-publishing and map-publishing functionality, and is currently compatible with Windows Live Spaces, SharePoint blogs, Blogger, LiveJournal, TypePad, WordPress, Telligent Community, PBlogs.gr, JournalHome, the MetaWeblog API, the Movable Type API, Blogengine, Squarespace, and all blogs that support RSD (Really Simple Discoverability). “

I have started playing around with Windows Live Writer plugins, as I discover plugins I’ll write a blog entry if I find a plugin to be impressive. In addition I have also started looking at the Live Writer API. If inspiration strikes I will attempt creating my own Live Writer Plugin.

[tweetmeme source=”DefaultSoftware” only_single=”false”]

Microsoft HelpBridge Disaster Response App

Last week Microsoft released a new free mobile App called HelpBridge. The App has been released for Windows Phone, Android and iOS, with the purpose intended around natural disaster response and relief operations.

HelpBridge can be used when a natural disaster occurs to connect friends and family being affected. Users can also provide help through HealthBridge in the form of donations or resources required by relief operations.

When setting up HealthBridge users need to provide contact details for a list of friends and family members. When disaster strikes HealthBridge can be used to contact a user’s friends and family by SMS, email or Facebook and indicate if the user is Ok or needs help. The phone’s GPS can also be used to provide location data.

Download HealthBridge here: Windows Phone Android iOS

Read more from Microsoft

[tweetmeme source=”DefaultSoftware” only_single=”false”]

Dewald Esterhuizen

Unknown's avatar

Blog Stats

  • 894,599 hits

Enter your email address to follow and receive notifications of new posts by email.

Join 91 other subscribers

Archives

RSS SoftwareByDefault on MSDN

  • An error has occurred; the feed is probably down. Try again later.