How to extract a password protected zip file using DotNetZip in C# and VB.NET

To extract (unzip) a password protected zip file using the Ionic DotNetZip Library, you can use the snippet below.

Samples

[tab name=”C# Sample”]

[/tab]
[tab name=”VB.NET Sample”]

[/tab]

[end_tabset]

If you have any questions or suggestions feel free to rate this snippet, post a comment or Contact Us via Email.

Related links:

Please rate this snippet

How to download a file using Python

To download a file using Python you can use the snippet below.

Sample Python

import urllib.request
import shutil

# file_name = target file name
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
    shutil.copyfileobj(response, out_file)

Please rate this snippet

How to delete .svn files and folders using Windows Batch Script

to delete .svn files and folders using Windows Batch Script you can use the following snippet.

Sample Windows Batch Script

FOR /R "C:\Users\CodeSnippets.Fesslersoft.de\Documents\Visual Studio 2013\Projects\ConsoleApplication" %%X IN (.svn) DO (RD /S /Q "%%X" 2>nul)

Replace C:\Users\CodeSnippets.Fesslersoft.de\Documents\Visual Studio 2013\Projects\ConsoleApplication with your Solution’s Path.

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 get free Drive Space in C# and VB.NET

To get free Drive Space in C# and VB.NET you can use the following snippet.

Sample C#

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetDiskFreeSpaceEx(string lpDirectoryName,out ulong lpFreeBytesAvailable,out ulong lpTotalNumberOfBytes,out ulong lpTotalNumberOfFreeBytes);

public static bool GetFreeDriveSpace(string path, out ulong freebytes)
{
	if (string.IsNullOrEmpty(path))
	{
		throw new ArgumentNullException("path");
	}

	if (!path.EndsWith("\\"))
	{
		path = String.Concat(path, "\\");
	}

	ulong lpFreeBytesAvailable;
	ulong lpTotalNumberOfBytes;
	ulong lpTotalNumberOfFreeBytes;

	if (GetDiskFreeSpaceEx(path, out lpFreeBytesAvailable, out lpTotalNumberOfBytes, out lpTotalNumberOfFreeBytes))
	{
		freebytes = lpFreeBytesAvailable;
		return true;
	}
	freebytes = 0;
	return false;
}

Sample VB.NET

<DllImport("kernel32.dll", SetLastError := True, CharSet := CharSet.Auto)> _
Private Shared Function GetDiskFreeSpaceEx(lpDirectoryName As String, ByRef lpFreeBytesAvailable As ULong, ByRef lpTotalNumberOfBytes As ULong, ByRef lpTotalNumberOfFreeBytes As ULong) As <MarshalAs(UnmanagedType.Bool)> Boolean
End Function

Public Shared Function GetFreeDriveSpace(path As String, ByRef freebytes As ULong) As Boolean
	If String.IsNullOrEmpty(path) Then
		Throw New ArgumentNullException("path")
	End If

	If Not path.EndsWith("\") Then
		path = [String].Concat(path, "\")
	End If

	Dim lpFreeBytesAvailable As ULong
	Dim lpTotalNumberOfBytes As ULong
	Dim lpTotalNumberOfFreeBytes As ULong

	If GetDiskFreeSpaceEx(path, lpFreeBytesAvailable, lpTotalNumberOfBytes, lpTotalNumberOfFreeBytes) Then
		freebytes = lpFreeBytesAvailable
		Return True
	End If
	freebytes = 0
	Return False
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