How to archive file from folder using ZipFile c# - c#

I have to take a file from a folder and make a archive in another folder.
I use this code but get an error:
************** Exception Text **************
System.IO.IOException: The directory name is invalid.
I use this code:
private void button1_Click(object sender, EventArgs e)
{
string Info = "";
string startPath = #"D:\dosfiles\SYNOPD\SYNOPD$$.PD\" + comboBox3.SelectedItem.ToString() + #"\" + comboBox2.SelectedItem.ToString() + #"\" + station;
string zipPath = #"D:\dosfiles\SYNOPD\" + comboBox1.SelectedItem.ToString() + "_" + comboBox2.SelectedItem.ToString() + "_" + comboBox3.SelectedItem.ToString() + ".zip";
if (File.Exists(zipPath))
{
File.Delete(zipPath);
ZipFile.CreateFromDirectory(startPath, zipPath);
Info += "Вашият архив е създаден в папка D:\\dosfiles\\SYNOPD\\" + comboBox1.SelectedItem.ToString() + "_" + comboBox2.SelectedItem.ToString() + "." + comboBox3.SelectedItem.ToString() + ".zip" + Environment.NewLine;
}
else
{
ZipFile.CreateFromDirectory(startPath, zipPath);
Info += "Вашият архив е създаден в папка D:\\dosfiles\\SYNOPD\\" + comboBox1.SelectedItem.ToString() + "_" + comboBox2.SelectedItem.ToString() + "." + comboBox3.SelectedItem.ToString() + ".zip" + Environment.NewLine;
}
this.Hide();
Form1 frm = new Form1();
frm.Show();
}

Related

File's last modified time not changing

I have written the following code in a Timer's Tick event to checking if the file modification time of an image has changed then copy that image and save it to another directory. Sometimes GetLastWrittenTime() doesn't change even though the file has already been overwritten.
if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp"))
{
DateTime filetime=File.GetLastWriteTime(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp");
if (!filetime.Equals(lastmMdifiedTime))
{
if (txtkapan.Text != "" && txtlot.Text != "")
{
if (reg.Read("AUTOPATH") == null || reg.Read("AUTOPATH").Equals(""))
{
Directory.CreateDirectory("D:\\" + txtkapan.Text + "\\" + txtlot.Text);
}
else
{
Directory.CreateDirectory(reg.Read("AUTOPATH")+"\\" + txtkapan.Text + "\\" + txtlot.Text);
}
string image_name;
if (txtlot.Text.Length <= 3 || txtparty.Text.Length <= 3 || txtkapan.Text.Length <= 3)
{
image_name = txtparty.Text.Substring(0, txtparty.Text.Length) + "_" + txtkapan.Text.Substring(0, txtkapan.Text.Length) + "_" + txtlot.Text.Substring(0, txtlot.Text.Length) + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH_mm") + ".jpg";
}
else
{
image_name = txtparty.Text.Substring(0, 3) + "_" + txtkapan.Text.Substring(0, 3) + "_" + txtlot.Text.Substring(0, 3) + "_" + DateTime.Now.ToString("yyyy-MM-dd_HH_mm") + ".jpg";
}
try
{
System.Drawing.Image img = System.Drawing.Image.FromFile(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp");
img.Save(reg.Read("AUTOPATH") + "\\" + txtkapan.Text + "\\" + txtlot.Text + "\\" + image_name, ImageFormat.Jpeg);
lastmMdifiedTime = File.GetLastWriteTime(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\CaptureMerge.bmp");
}
catch (Exception ex)
{
MessageBox.Show("Exception:" + ex.ToString());
}
}
else { }
}
}
Please tell me what is wrong in my code.

OneNote UpdatePageContent

I am trying to update the page content in OneNote through my C# application. Here is the code I have for doing this:
private static void SetElementInPage(string pageId)
{
Microsoft.Office.Interop.OneNote.Application m_app = new Microsoft.Office.Interop.OneNote.Application();
string strPageContent = "<one:Page xmlns:one=\"http://schemas.microsoft.com/office/onenote/2010/onenote\" ID=\"{0}\" >" +
"<one:Outline>" +
"<one:Position x=\"36.0\" y=\"86.4000015258789\" z=\"0\" />" +
"<one:Size width=\"117.001953125\" height=\"40.28314971923828\" />" +
"<one:OEChildren>" +
"<one:OE>" +
"<one:T><![CDATA[This is a sample data added to test out OneNote API functionality. Following is a list item.]]></one:T>" +
"</one:OE>" +
"</one:OEChildren>" +
"<one:OEChildren indent=\"2\">" +
"<one:OE alignment=\"left\">" +
"<one:List>" +
"<one:Bullet bullet=\"2\" fontSize=\"11.0\" />" +
"</one:List>" +
"<one:T><![CDATA[A for Apple]]></one:T>" +
"</one:OE>" +
"<one:OE alignment=\"left\">" +
"<one:List>" +
"<one:Bullet bullet=\"2\" fontSize=\"11.0\" />" +
"</one:List>" +
"<one:T><![CDATA[B for Ball]]></one:T>" +
"</one:OE>" +
"<one:OE alignment=\"left\">" +
"<one:List>" +
"<one:Bullet bullet=\"2\" fontSize=\"11.0\" />" +
"</one:List>" +
"<one:T><![CDATA[C for Cat]]></one:T>" +
"</one:OE>" +
"</one:OEChildren>" +
"</one:Outline>" +
"</one:Page>";
strPageContent = string.Format(strPageContent, pageId);
m_app.UpdatePageContent(strPageContent);
}
On the final line m_app.UpdatePageContent(strPageContent); I am getting an error that reads:
An exception of type 'System.Runtime.InteropServices.COMException' occurred in Microsoft.Office.Interop.OneNote.dll but was not handled in user code
The method setElementInPage(string pageId) is also called in the code below:
private async void ThisAddIn_Startup(object sender, System.EventArgs e)
{
GetNamespace();
string notebookId = GetObjectId(null, Microsoft.Office.Interop.OneNote.HierarchyScope.hsNotebooks, "Aaron # Microsoft");
string sectionId = GetObjectId(notebookId, Microsoft.Office.Interop.OneNote.HierarchyScope.hsSections, "New Section 1");
string firstPageId = GetObjectId(sectionId, Microsoft.Office.Interop.OneNote.HierarchyScope.hsPages, "My Page");
SetElementInPage(firstPageId);
Console.Read();
}
What could be causing this issue? Any help is appreciated, thanks.

Writing Text File to Folder on Desktop

I'm wondering how do you write a text file to a specific location on the desktop such as C:\Users\tommy\desktop\transaction\ using StreamWriter?
private void CreateTransaction_Click(object sender, EventArgs e)
{
StreamWriter outputFile;
outputFile = File.CreateText (TID.ToString()+".txt");
outputFile.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
outputFile.WriteLine("Initial Amount" + " " +AmountLabel.Text);
outputFile.WriteLine("Date Invested" +" " +DateLabel.Text);
outputFile.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
outputFile.WriteLine("Rate Chosen" + " " + RateLabel.Text);
outputFile.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
outputFile.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
outputFile.Close();
MessageBox.Show("Transaction file for Transaction: " + TransactionIDLabel.Text + "Was Created", "Transaction File");
}
If you know the path,
FileStream fs = new FileStream(#"C:\Users\tommy\desktop\transaction\\result.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.BaseStream.Seek(0, SeekOrigin.End);
sw.WriteLine("Investor :" +" " + InvestorNameLabel.Text);
sw.WriteLine("Initial Amount" + " " +AmountLabel.Text);
sw.WriteLine("Date Invested" +" " +DateLabel.Text);
sw.WriteLine("Period Chosen" + " "+DaysInvestedLabel.Text);
sw.WriteLine("Rate Chosen" + " " + RateLabel.Text);
sw.WriteLine("Total Interest" + " " +InterestAmountLabel.Text);
sw.WriteLine("Transaction Number :" + " " + TransactionIDLabel.Text);
sw.Flush();
sw.Close();
else create a file inside the desktop folder and do the above
Use Environment.SpecialFolder to get the path to the desktop.
string strPath = Environment.GetFolderPath(
System.Environment.SpecialFolder.DesktopDirectory);

GitHub API update file

I'm trying to update a file via the GitHub API.
I've got everything setup, and in the end the actual file is updated, which is a good thing.
However, let's say I've got these 2 files in my repo
FileToBeUpdated.txt
README.md
And then I run my program
The FileToBeUpdated.txt is updated, like it should, however the README.md is deleted.
This is the code with the 5 steps to update the file:
private static void Main()
{
string shaForLatestCommit = GetSHAForLatestCommit();
string shaBaseTree = GetShaBaseTree(shaForLatestCommit);
string shaNewTree = CreateTree(shaBaseTree);
string shaNewCommit = CreateCommit(shaForLatestCommit, shaNewTree);
SetHeadPointer(shaNewCommit);
}
private static void SetHeadPointer(string shaNewCommit)
{
WebClient webClient = GetMeAFreshWebClient();
string contents = "{" +
"\"sha\":" + "\"" + shaNewCommit + "\", " +
// "\"force\":" + "\"true\"" +
"}";
// TODO validate ?
string downloadString = webClient.UploadString(Constants.Start + Constants.PathToRepo + "refs/heads/master", "PATCH", contents);
}
private static string CreateCommit(string latestCommit, string shaNewTree)
{
WebClient webClient = GetMeAFreshWebClient();
string contents = "{" +
"\"parents\" :[ \"" + latestCommit + "\" ], " +
"\"tree\":" + "\"" + shaNewTree + "\", " +
"\"message\":" + "\"test\", " +
"\"author\": { \"name\": \""+ Constants.Username +"\", \"email\": \""+ Constants.Email+"\",\"date\": \"" + DateTime.UtcNow.ToString("s", CultureInfo.InvariantCulture) + "\"}" +
"}";
string downloadString = webClient.UploadString(Constants.Start + Constants.PathToRepo + "commits", contents);
var foo = JsonConvert.DeserializeObject<CommitRootObject>(downloadString);
return foo.sha;
}
private static string CreateTree(string shaBaseTree)
{
WebClient webClient = GetMeAFreshWebClient();
string contents = "{" +
"\"tree\" :" +
"[ {" +
"\"base_tree\": " + "\"" + shaBaseTree + "\"" + "," +
"\"path\": " + "\"" + Constants.FileToChange + "\"" + " ," +
"\"content\":" + "\"" + DateTime.Now.ToLongTimeString() + "\"" +
"} ]" +
"}";
string downloadString = webClient.UploadString(Constants.Start + Constants.PathToRepo + "trees", contents);
var foo = JsonConvert.DeserializeObject<TreeRootObject>(downloadString);
return foo.sha;
}
private static string GetShaBaseTree(string latestCommit)
{
WebClient webClient = GetMeAFreshWebClient();
string downloadString = webClient.DownloadString(Constants.Start + Constants.PathToRepo + "commits/" + latestCommit);
var foo = JsonConvert.DeserializeObject<CommitRootObject>(downloadString);
return foo.tree.sha;
}
private static string GetSHAForLatestCommit()
{
WebClient webClient = GetMeAFreshWebClient();
string downloadString = webClient.DownloadString(Constants.Start + Constants.PathToRepo + "refs/heads/master");
var foo = JsonConvert.DeserializeObject<HeadRootObject>(downloadString);
return foo.#object.sha;
}
private static WebClient GetMeAFreshWebClient()
{
var webClient = new WebClient();
webClient.Headers.Add(string.Format("Authorization: token {0}", Constants.OAuthToken));
return webClient;
}
Which part am I missing? Am I using the wrong tree to start from?
It seems that in the function CreateTree I should set the base_tree at the root level, not at the level of each tree I create.
So in the function CreateTree the contents become this:
string contents = "{" +
"\"base_tree\": " + "\"" + shaBaseTree + "\"" + "," + // IT'S THIS LINE!
"\"tree\" :" +
"[ {" +
"\"path\": " + "\"" + Constants.FileToChange + "\"" + " ," +
"\"content\":" + "\"" + DateTime.Now.ToLongTimeString() + "\"" +
"} ]" +
"}";
Updated GitHub documentation: https://github.com/Snakiej/developer.github.com/commit/2c4f93003703f68c4c8a436df8cf18e615e293c7

best way to handle conditional statement

I have the following condition using in my code but that doesn't look very efficient,is this any better way to handle ?
if (ic = filename.Contains(".wmv"))
{
if (bitnumber > 400)
{
path = "ftp://" + ftpServerIP + "/" + "media" + "/" + "lib" + "/" + programName + "/" + date + "/";
UploadCondition(path, filename);
//return path;
}
}
if (ic = filename.Contains(".wmv"))
{
if (bitnumber < 400)
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
//return path;
}
}
if (ic = filename.Contains(".m4v"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".mp4"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".flv"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".mpg"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".aac"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
if (ic = filename.Contains(".mp3"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
Break it up in other classes like:
public class AudioFileValidator
{
private List<string> _extensions = new List<string>{".aac", ".mp3"};
public bool IsValid(string filename)
{
if (!_extensions.Contains(Path.GetExtension(filename))
return false;
//validate bitrate etc
}
}
Usage:
var audioValidator = new AudioFileValidator();
if (audioValidator.IsValid(filename))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
var videoValidator = new VideoFileValidator();
if (videoValidator.IsValid(filename))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
By doing so you'll get classes with a single responsibility which can be reused in other places and which are easy to unit test.
You could even take it further and introduce a new interface called IMediaFileValidator which all validators implement. and do something like:
foreach (var validator in validators)
{
if (validator.IsValid(filename))
{
// use info from the validator to build the path
var mediaName = validator.MediaName;
path = "ftp://" + ftpServerIP + "/" + mediaName + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
break;
}
}
Which would also make your code adhere to Open/Closed principle.
You will need a lot of refactoring. Here are couple of ideas to get you started:
Use String.Format and passed in only value that changed to save you all the repeating the text
Build a dictionary of Extension/Ext-Combination key and set the value to the the destination path. You will then only require one lookup than big nesting if - else statements
Use Path.GetExtension rather than Contains to be more accurate
Eg.
string formatStringNews = "ftp://{0}/news/{1}/";
string formatStringMedia = "ftp://{0}/media/{1}/";
dictionary["wmv"] = formatStringMedia;
dictionary["mp3"] = formatStringNews;
....
string key = Path.GetExtension(filename);
path = string.Format(dictionary[key], serverName, programName);
Something like this is a nice short solution to your problem and I believe it handles all of the cases your if statements are handling.
String[] videoExtensions = { "wmv", "m4v", "mp4", "flv" };
String[] audioExtensions = { "aac", "mp3" };
String ext = Path.GetExtension(filename).ToLower();
String path = "ftp://" + ftpServerIP + "/";
if (-1 != Array.IndexOf(videoExtensions, ext)) {
if ("wmv".equals(ext) && bitnumber > 400)
path += "media/lib/" + programName + "/" + date + "/";
else
path += "mpegmedia/news/" + programName + "/video/podcast/";
}
else if (-1 != Array.IndexOf(audioExtensions, ext)) {
path += "mpegmedia/news/" + programName + "/audio/podcast/";
}​​​​​​​​​​​
else {
// handle unknown extension types as desired
}
UploadCondition(path, filename);
Use a switch statement and System.IO.Path.GetExtension.
select (System.IO.Path.GetExtension(filename))
{
case ".wmv":
if (bitnumber > 400)
{
path = "ftp://" + ftpServerIP + "/" + "media" + "/" + "lib" + "/" + programName + "/" + date + "/";
UploadCondition(path, filename);
//return path;
}
else
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
//return path;
}
break;
case ".m4v":
case ".mp4":
case ".flv":
case ".mpg":
case ".mp3":
default:
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
break;
}
}
I'm guessing you'll want variations for the last block, but this should be easy enough to modify.
At the very least you could convert it into an if/elseif statement:
if (ic....)
{
...
} else if (ic...) {
...
}
I assume, at a time your filename will be either be .m4v, .flv,.mp4 etc...so here goes the code..
if (ic = filename.Contains(".wmv"))
{
if (bitnumber > 400)
{
path = "ftp://" + ftpServerIP + "/" + "media" + "/" + "lib" + "/" + programName + "/" + date + "/";
UploadCondition(path, filename);
//return path;
}
else
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
//return path;
}
}
else if (ic = filename.Contains(".m4v"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".mp4"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".flv"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".mpg"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "video" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".aac"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else if (ic = filename.Contains(".mp3"))
{
path = "ftp://" + ftpServerIP + "/" + "mpegmedia" + "/" + "news" + "/" + programName + "/" + "audio" + "/" + "podcast" + "/";
UploadCondition(path, filename);
}
else
{
//No Match found
}
and the best approach would be to use Switch(fileExtn)
You could perhaps make it a bit simpler like
if (filename.Contains(".wmv"))
// path = set the path as you require
and after all the ifs end call your method
UploadCondition(path, filename);
Better would be to extract the extension .wmv, .m4v from filename and make this into a switch whereby you set the path.

Categories