Extracting .zip file into folder C# - c#

I have problem when I try to create code for extracting .zip file into a folder, before I show you code, I want to tell you what I need to do?
Its simple, I want to write code so that when a user clicks on a button, it deletes a directory, and then downloads a new .zip file and extracts it at the same directory and name which was deleted... Its something like restoring directory to default form..
I successfully wrote code for deleting the directory and downloading .zip file but I cant write code for extracting that .zip ...
Here is the code
private void button2_Click(object sender, EventArgs e)
{
// Is file downloading yet?
if (webClient != null)
return;
var sprdir = new DirectoryInfo(#"cstrike/sprites");
string sprzippath = #"cstrike/sprites.zip";
string extzippath = #"cstrike";
if (!sprdir.Exists)
{
webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/sprites.zip"), #"cstrike/sprites.zip");
}
else
{
sprdir.Attributes = sprdir.Attributes & ~FileAttributes.ReadOnly;
sprdir.Delete(true);
webClient = new WebClient();
webClient.DownloadFileAsync(new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/sprites.zip"), #"cstrike/sprites.zip");
}
}
And yea, I tried with using System.IO and System.IO.Compress and ZipFile.ExtractToDirectory and ExtractToDirectory, no one working... Just get red line below the text..

So first you need to add assembly System.IO.Compression.FileSystem into your projects.
Second thing is that you are using DownloadFileAsync which probably was not yet completed so your extraction fails (because no file exists yet)
The 3rd is that you are not creating the folder if it does not exists and that makes WebClient.DownloadFileAsync fail.
you need to register to the event where DownlodFileCompleted and to the extraction there.
here is an example:
using System;
using System.ComponentModel;
using System.IO;
using System.Net;
using System.Windows.Forms;
using System.IO.Compression;
namespace Stack
{
public partial class Form1 : Form
{
WebClient webClient;// = new WebClient();
const string basPath = #"D:\test";
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
// Is file downloading yet?
if (webClient != null)
return;
//var sprdir = new DirectoryInfo(#"cstrike/sprites");
var sprdir = new DirectoryInfo(basPath);
string sprzippath = $"{basPath}/sprites.zip";
string extzippath = #"cstrike";
if (!sprdir.Exists)
{
Directory.CreateDirectory(basPath);
webClient = new WebClient();
webClient.DownloadFileCompleted += ExtratcZip;
webClient.DownloadFileAsync(
new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/sprites.zip"),
$"{basPath}/sprites.zip");
}
else
{
sprdir.Attributes = sprdir.Attributes & ~FileAttributes.ReadOnly;
sprdir.Delete(true);
Directory.CreateDirectory(basPath);
webClient = new WebClient();
webClient.DownloadFileCompleted += ExtratcZip;
webClient.DownloadFileAsync(
new Uri("https://sipi-portfolio.000webhostapp.com/csfiledownload/sprites.zip"),
$"{basPath}/sprites.zip");
}
}
private void ExtratcZip(object sender, AsyncCompletedEventArgs e)
{
ZipFile.ExtractToDirectory($"{basPath}/sprites.zip", $"{basPath}");
}
}
}
hope it helps.

Related

Call a automatic Download URL without opening the Browser

I have a small problem with downloading a file.
I have used windows Forms and need to download several files. They all are avaiable through a link that, when its opened automatically downloads the file.
I tried several things like WebCient or httpWebrequest but it all doesnt work.
Do you have any idea how i can launch this link without opening the browser every time and safe the file to a specific folder.
foreach (var doc in newDocs)
{
using (var wb = new WebClient())
{
MessageBox.Show("link" <- to cehck the if its the correct file;
HttpWebRequest request = WebRequest.Create("link") as HttpWebRequest;
wb.DownloadFile("link" <- 'link' cause its sensitive data.);
}
}
Hope it will help you.
void Download()
{
using (WebClient client = new WebClient())
{
client.DownloadProgressChanged += Client_DownloadProgressChanged;
client.DownloadFileCompleted += Client_DownloadFileCompleted;
client.DownloadFileAsync(new Uri("url"), #"filepath");
}
}
private void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
//throw new NotImplementedException();
}
private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
//throw new NotImplementedException();
}

How can I use folderBrowserDialog1.SelectedPath in C# to let users select a download path?

I am trying to make a download tool for a project of mine (In C#).
How ever, the users should be able to set a download folder by themselves using folderBrowserDialog1.SelectedPath.
Currently I am downloading like this:
private void button1_Click(object sender, EventArgs e)
{
String Pfad = TextBox1.Text;
WebClient Client = new WebClient();
Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
Client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);
Client.DownloadFileAsync(new Uri("http://dl.4players.de/ts/releases/3.0.13.6/teamspeak3-server_win64-3.0.13.6.zip"), Pfad);
}
As you can see the users have to type in the path, but it should be selectable via folderBrowserDialog1.SelectedPath.
thanks!
I'm not sure what you're stuck on, you've correctly identified that a FolderBrowserDialog would be a good tool to use.
private void button1_Click(object sender, EventArgs e)
{
// Shows the FolderBrowserDialog and prevents further actions until a choice is made
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK) // Checks they selected a path
{
string Pfad = folderBrowserDialog1.SelectedPath;
WebClient Client = new WebClient();
Client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
Client.DownloadFileCompleted += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);
Client.DownloadFileAsync(new Uri("http://dl.4players.de/ts/releases/3.0.13.6/teamspeak3-server_win64-3.0.13.6.zip"), Pfad);
}
}

Getting error when compressing file with ZipFile

I am using Windows form application. In my application I am using FolderBrowserDialog, textbox1 and two buttons. In my textbox I am passing folder. From folder it will select particular file type. After getting such file type I need to convert it using ZipFile i.e. Iconic.zip. After retrieving particular file type it is showing me error of FileNotfound. For testing purpose I tried to display retrived file to listbox and it is working well. But when I am calling via ZipFile it is giving me error, can't figure out what error is.
namespace WinDataStore
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
//notification to user
return;
}
string[] extensions = { ".xml",".ddg" };
string[] dizin = Directory.GetFiles(textBox1.Text, "*.*",SearchOption.AllDirectories)
.Where(f => extensions.Contains(new FileInfo(f).Extension.ToLower())).ToArray();
// listBox1.Items.AddRange(dizin);
using (ZipFile zip = new ZipFile())
{
zip.AddFile("dizin", "files");
zip.Save("z.zip");
}
}
}
}
You can't pass a variable as a string like this:
string[] dizin = ...;
zip.AddFile("dizin", "files");
Instead use it like this:
zip.AddFile(dizin, "files");
Or more likely you need to loop:
foreach(var file in dizin)
{
zip.AddFile(file, "files");
}
Or if you are using Ionic Zip Library use the AddFiles method:
zip.AddFiles(dizin, "files");
This below code solved my problem
using (ZipFile zip = new ZipFile())
{
foreach(var file in dizin)
{
zip.AddFile(file);
}
zip.Save("z.zip");
}

Reading Text Files in FileSystemWatcher in C# getting Error of File already in Use by another resource

Hello I want to use FileSystemWatcher in C Sharp to watch for the text files coming in a folder Reading There Text and uploading Their text to a Web Server with a GET Request in C Sharp
but the problem is that when i try it and first time when some file opened it works fine but on second time when a file come to the directory it will show me that the file is already used by another application or the resource is not free its already allocated.
here is the small code for it
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net;
namespace FileChangeNotifier
{
public partial class frmNotifier : Form
{
private StringBuilder m_Sb;
private bool m_bDirty;
private System.IO.FileSystemWatcher m_Watcher;
private bool m_bIsWatching;
public frmNotifier()
{
InitializeComponent();
m_Sb = new StringBuilder();
m_bDirty = false;
m_bIsWatching = false;
}
private void btnWatchFile_Click(object sender, EventArgs e)
{
if (m_bIsWatching)
{
m_bIsWatching = false;
m_Watcher.EnableRaisingEvents = false;
m_Watcher.Dispose();
btnWatchFile.BackColor = Color.LightSkyBlue;
btnWatchFile.Text = "Start Watching";
}
else
{
m_bIsWatching = true;
btnWatchFile.BackColor = Color.Red;
btnWatchFile.Text = "Stop Watching";
m_Watcher = new System.IO.FileSystemWatcher();
if (rdbDir.Checked)
{
m_Watcher.Filter = "*.*";
m_Watcher.Path = txtFile.Text + "\\";
}
else
{
m_Watcher.Filter = txtFile.Text.Substring(txtFile.Text.LastIndexOf('\\') + 1);
m_Watcher.Path = txtFile.Text.Substring(0, txtFile.Text.Length - m_Watcher.Filter.Length);
}
if (chkSubFolder.Checked)
{
m_Watcher.IncludeSubdirectories = true;
}
m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
m_Watcher.Created += new FileSystemEventHandler(OnChanged);
m_Watcher.EnableRaisingEvents = true;
}
}
private void OnChanged(object sender, FileSystemEventArgs e)
{
if (!m_bDirty)
{
readFile(e.FullPath);
m_Sb.Remove(0, m_Sb.Length);
m_Sb.Append(e.FullPath);
m_Sb.Append(" ");
m_Sb.Append(e.ChangeType.ToString());
m_Sb.Append(" ");
m_Sb.Append(DateTime.Now.ToString());
m_bDirty = true;
}
}
private void readFile(String filename) {
String line = "";
if (File.Exists(filename))
{
try{
StreamReader sr = new StreamReader(filename);
//code for multiline reading but i need only one line so i am going to change he code
/* while ((line = sr.ReadLine()) != null)
{
MessageBox.Show(line);
}
*/
line = sr.ReadLine();
MessageBox.Show(line);
uploadDataToServer(line);
sr.Close();
} catch(IOException e){
MessageBox.Show(e.Message);
}
}
}
private void uploadDataToServer(String data) {
String url = "http://209.90.88.135/~lilprogr/?data="+data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream resStream = response.GetResponseStream();
}
}
}
To handle multiple change notifications, go here and look for #BaBu's answer.
Also,
If all you need is to read from the file,
Have you tried to open it in Shared Mode?

Streamreader problems

I'm a real noob to C# trying to write a small XML replacer program based on a short code a friend of mine used in one of his apps..
I'm having trouble with this line:
StreamReader sr = new StreamReader(textBox1.Text);
I get an error: "Empty path name is not legal."
why doesn't this work?
the code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace ReplaceMe
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
StreamReader sr = new StreamReader(textBox1.Text);
StreamWriter sw = new StreamWriter(textBox1.Text.Replace(".", "_new."));
string cur = "";
do
{
cur = sr.ReadLine();
cur = cur.Replace(textBox2.Text, textBox3.Text);
sw.WriteLine(cur);
}
while (!sr.EndOfStream);
sw.Close();
sr.Close();
MessageBox.Show("Finished, the new file is in the same directory as the old one");
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = openFileDialog1.FileName;
}
}
}
}
Thanks in advance :)
That is because your textBox1 doesn't contain text at the moment you create StreamReader. You set textBox1 text in button1_Click, so you have to create StreamReader in that method.
You should make sure the file exists before you try to access it, it seems you deliver an empty string as a filename.
try accessing the file only when:
if (File.Exists(textBox1.Text))
{
//Your Code...
}
the value of textbox1 is null or empty. also, if you want to manipulate xml look into the objects of the System.Xml namespace. These objects are designed specifically for working with XML.
it's because you're setting an empty string in StreamReader constructor.
I recommend you do a simple validation before read file.
as this:
string fileName = textBox1.Text;
if(String.IsNullOrEmpty(fileName)) {
//textbox is empty
} else if(File.Exists(fileName)) {
//file not exists
} else {
// read it
StreamReader sr = new StreamReader(fileName);
//..
}
Note: it is not right way to manipulate xml files.
check out the XML documentation for more info.

Categories