How to check if a variable exists in Python

To check if a variable exists in Python, you can use the snippet below.

Sample Python

if 'myVariable' in locals(): # myVariable exists locally.
if 'myVariable' in globals(): # myVariable exists globally.

Please rate this snippet

How to check if a printer exists in C# and VB.NET

To check if a printer exists in C# and VB.NET you can use the following snippet.

Sample C#

public static bool PrinterExists(string printerName)
{
	if (String.IsNullOrEmpty(printerName)) {  throw new ArgumentNullException("printerName");}
	return PrinterSettings.InstalledPrinters.Cast<string>().Any(name => printerName.ToUpper().Trim() == name.ToUpper().Trim());
}

Sample VB.NET

Public Shared Function PrinterExists(printerName As String) As Boolean
	If String.IsNullOrEmpty(printerName) Then
		Throw New ArgumentNullException("printerName")
	End If
	Return PrinterSettings.InstalledPrinters.Cast(Of String)().Any(Function(name) printerName.ToUpper().Trim() = name.ToUpper().Trim())
End Function

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

How to check if file or folder exists in Powershell

To check if file or folder exists in Powershell you can use the following snippet.

Sample Powershell

for files use it like this

if(test-path "C:\Users\Codesnippets\Desktop\Test.xml") 
{ 
	echo "exists!" 
} 
else 
{ 
	echo "not exists!" 
}

for folders/directories use it like this

if(test-path "C:\Users\Codesnippets\Desktop") 
{ 
	echo "exists!" 
} 
else 
{ 
	echo "not exists!" 
}

Please rate this snippet

How to check if a file exists in Java

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

Sample Java

String filePath = "C:\\Users\\Codesnippets\\Desktop\\Test.xml";
File file = new File(filePath);
if (file.exists()) {
	System.out.println("file " + filePath + " does exists!");
} 
else {
	System.out.println("file " + filePath +  " does not exists!");
}

Please rate this snippet