Posts Tagged ‘file’

Using The At Symbol (@) With Strings

Defining the @ symbol prior to the assigning a string value will prevent the need for doubling the backslash (\) in C#. The at symbol (@) simply ignores escape characters. This is useful when accessing a directory local to the server. For example, you may want to store the local directory path in a string. Without using the at symbol (@), it would look similar to the following:

string directoryPath = "C:\\uploadedFiles\\pdfs";

Note that in the above example, each backslash is needs to be doubled. However, with the at symbol (@), it is both easier to read and type because we can keep the original single backslash format.

string directoryPath = @"C:\uploadedFiles\pdfs";

Just another trick in C# that may not be blatantly obvious, but very useful. Note that using the at symbol (@) can can be used sparing as in the demonstrated example below:

string directoryPath = "C:\\uploadedFiles" + @"\pdfs";

In the example above, the at symbol (@) was not used in the first half, but was used in the second half. Not sure why you would use this third example in this case, but just remember that it is an option.

Check If a Local File Exists in C#

Web applications often involve reading from and writing to files local to the web application server. In the case of reading from a file, errors may occur if the proper checks are not in place. One popular way of insuring errors don’t occur during runtime is to check if a file exists before attempting to read the file.

if (File.Exists("C:\\testfile.txt"))
{
   return true;
}
else
{
   return false;
}

This method utilizes the Exists function, part of the File class, to check if a file can be found at the specified directory. The string must be reachable from the server on which the web application resides. When expressing the input string, be sure to properly format your directory and file with double back slashes. To use File.Exists, be sure to include the following at the top of your file.

using System.IO;