How to get the path of the active app.config file in C# and VB.NET

To get the path of the active app.config file in C# and VB.NET you can use the following snippet

Sample C#

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile;

Sample VB.NET

AppDomain.CurrentDomain.SetupInformation.ConfigurationFile

Please rate this snippet

How to Remove Illegal Filename Characters in C# and VB.NET

To Remove Illegal Filename Characters in C# and VB.NET you can use the following snippet.

Sample C#

public static string RemoveIllegalFileNameChars(string input, string replacement="")
{
	var regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
	var r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
	return r.Replace(input, replacement);
}

Sample VB.NET

Public Shared Function RemoveIllegalFileNameChars(input As String, Optional replacement As String = "") As String
	Dim regexSearch = New String(Path.GetInvalidFileNameChars()) & New String(Path.GetInvalidPathChars())
	Dim r = New Regex(String.Format("[{0}]", Regex.Escape(regexSearch)))
	Return r.Replace(input, replacement)
End Function

Please rate this snippet

How to get the executable filename in C# and VB.NET

To get the executable filename in C# and VB.NET you can use one the following methods.

Sample C#

//prefered way to retrieve exe filename
Console.WriteLine(Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName));
 

Console.WriteLine(AppDomain.CurrentDomain.FriendlyName); //can cause problems when using click once, also this property does not always returns the right result.

Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().Location)); //can fail when used in wcf application.
Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase)); //better if shadow copy feature is active, but can fail when used in wcf application
Console.WriteLine(Path.GetFileName(Assembly.GetEntryAssembly().Location));

Sample VB.NET

'prefered way to retrieve exe filename
Console.WriteLine(Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName))


Console.WriteLine(AppDomain.CurrentDomain.FriendlyName)
'can cause problems when using click once, also this property does not always returns the right result.
Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().Location))
'can fail when used in wcf application.
Console.WriteLine(Path.GetFileName(Assembly.GetExecutingAssembly().CodeBase))
'better if shadow copy feature is active, but can fail when used in wcf application
Console.WriteLine(Path.GetFileName(Assembly.GetEntryAssembly().Location))

Please rate this snippet

How to check if Directory has Files in C# and VB.NET

To check if Directory has Files in C# and VB.NET you can use the following snippet.

Sample C#

public static bool HasFilesInFolder(DirectoryInfo folder)
{
	return folder.GetFiles("*.*").Any();
}

Sample VB.NET

Public Shared Function HasFilesInFolder(folder As DirectoryInfo) As Boolean
	Return folder.GetFiles("*.*").Any()
End Function

Please rate this snippet

How to read a File to Textreader in C# and VB.NET

To read a File to Textreader in C# and VB.NET you can use the following snippet.

Sample C#

TextReader reader = File.OpenText(@"C:\dummy.txt");

Sample VB.NET

Dim reader As TextReader = File.OpenText(@"C:\dummy.txt")

Please rate this snippet

How to change the File extension in C# and VB.NET

To change the File extension in C# and VB.NET you can use the following snippet.

Sample C#

public static FileInfo ChangeExtension(FileInfo file, string newExtension)
{
	if (!newExtension.StartsWith("."))
	{
		newExtension = "." + newExtension;
	}
	var fileName = string.Concat(Path.GetFileNameWithoutExtension(file.FullName), newExtension);
	if (File.Exists(fileName))
	{
		File.Delete(fileName);
	}
	File.Move(file.FullName,fileName);
	if (File.Exists(fileName))
	{
		File.Delete(file.FullName);
	}
	return new FileInfo(fileName);
}

Sample VB.NET

Public Shared Function ChangeExtension(file__1 As FileInfo, newExtension As String) As FileInfo
	If Not newExtension.StartsWith(".") Then
		newExtension = Convert.ToString(".") & newExtension
	End If
	Dim fileName = String.Concat(Path.GetFileNameWithoutExtension(file__1.FullName), newExtension)
	If File.Exists(fileName) Then
		File.Delete(fileName)
	End If
	File.Move(file__1.FullName, fileName)
	If File.Exists(fileName) Then
		File.Delete(file__1.FullName)
	End If
	Return New FileInfo(fileName)
End Function

Please rate this snippet

How to copy a Folder/Directory recursive in C# and VB.NET

How to copy a Folder/Directory recursive in C# and VB.NET.

Sample C#

public void RecursiveFolderCopy(string sourceDirectory, string destinationDirectory, bool recursive)
{
	var dir = new DirectoryInfo(sourceDirectory);
	var dirs = dir.GetDirectories();

	if (!dir.Exists)
	{
		throw new DirectoryNotFoundException(
			String.Format("Source directory {0} does not exist!",
				sourceDirectory));
	}

	if (!Directory.Exists(destinationDirectory))
	{
		Directory.CreateDirectory(destinationDirectory);
	}

	var files = dir.GetFiles();
	foreach (var file in files)
	{
		var temppath = Path.Combine(destinationDirectory, file.Name);
		file.CopyTo(temppath, false);
	}

	if (!recursive)
	{
		return;
	}
	foreach (var subdir in dirs)
	{
		var temppath = Path.Combine(destinationDirectory, subdir.Name);
		RecursiveFolderCopy(subdir.FullName, temppath, recursive);
	}
}

Sample VB.NET

Public Sub RecursiveFolderCopy(ByVal sourceDirectory As String, ByVal destinationDirectory As String, ByVal recursive As Boolean)
        Dim dir As var = New DirectoryInfo(sourceDirectory)
        Dim dirs As var = dir.GetDirectories
        If Not dir.Exists Then
            Throw New DirectoryNotFoundException(String.Format("Source directory {0} does not exist!", sourceDirectory))
        End If
        If Not Directory.Exists(destinationDirectory) Then
            Directory.CreateDirectory(destinationDirectory)
        End If
        Dim files As var = dir.GetFiles
        For Each file As var In files
            Dim temppath As var = Path.Combine(destinationDirectory, file.Name)
            file.CopyTo(temppath, false)
        Next
        If Not recursive Then
            Return
        End If
        For Each subdir As var In dirs
            Dim temppath As var = Path.Combine(destinationDirectory, subdir.Name)
            RecursiveFolderCopy(subdir.FullName, temppath, recursive)
        Next
    End Sub

Please rate this snippet

How to read a file to string in Java

To read a file to string in Java you can use the following snippet.

Sample Java

public static string readFileToString(FileInputStream _fileInputStream)
{
	try {  
		DataInputStream dataInputStream = new DataInputStream (_fileInputStream);  
		byte[] Bytes = new byte[dataInputStream.available ()];  
		dataInputStream.readFully (Bytes);  
		dataInputStream.close ();  
		String result = new String (Bytes, 0, Bytes.length, "Cp850");  
		return result;  
	}  
	catch (Exception e) {  
		e.printStackTrace();  
		return "";
	} 
}

Please rate this snippet

How to check if a file exists in C++

To check if a file exists in C++ you can use the following snippet.

Sample C++

#include <sys/stat.h>

inline bool fileExists (const std::string& fileName) {
	struct stat buff;   
	return (stat (fileName.c_str(), &buff) == 0); 
}

Please rate this snippet