Friday, January 23, 2009

C#: Update File attributes Readonly to normal mode

Here’s a nice little piece of code you can use to change file attributes of a particular file, its particularly useful when you’re trying to delete a read only file.



string savedCardFilePath = "My absolute file path";

if (File.Exists(savedCardFilePath))
{

// Remove readonly attribute off of the file if it exists before execution

if(File.GetAttributes(savedCardFilePath) == FileAttributes.ReadOnly)
File.SetAttributes(savedCardFilePath, FileAttributes.Normal);
File.Delete(savedCardFilePath);

}

.NET: Generate Random Numbers

Actually these are not exactly "true" random numbers. These are actually pseudo-random numbers, which means that they give you an illusion that they’re being generated randomly.

It’s very simple: There’s a class called System.Random. and the rest is as simple as this:-

In C#,


Random r = new Random(0);
int num = r.Next(0,999999);


in VB .NET



dim r as Random = new Random(0)
dim num as Int = r.Next(0,999999)

.NET: Extact FileName from Path

You can Extract the Filename by using Path Class from System.IO

In C#



string filename = Path.GetFileName("D:\My Documents\myimg.jpg");



In VB .NET



Dim fileName as String = Path.GetFIleName(”D:\My Documents\myimg.jpg”)

SQL: Delete Table If Exists

To Drop a table, if table exists, use the following Query



IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE table_name = 'TableToDelete') DROP TABLE TableToDelete