how to zip the file using ionic library - c#

I have done this one for backup my database
its working fine ....
private void backupDatabase()
{
txtbackup.AppendText("Starting Backup...");
Process sd = null;
const string backupcmd = #"C:\wamp\www\access\mysqldump.exe";
string filepath = #"C:\folder\Access\";
string dbHost = "local";
string dbuser = "root";
string dbName = "access";
string backupName = "Backup.sql";
ProcessStartInfo r1 = new ProcessStartInfo(backupcmd, string.Format("-h {0} -u {1} {2} -r {3}", dbHost, dbuser, dbName, backupName));
r1.CreateNoWindow = true;
r1.WorkingDirectory = filepath;
r1.UseShellExecute = false;
r1.WindowStyle = ProcessWindowStyle.Minimized;
r1.RedirectStandardInput = false;
sd = Process.Start(r1);
sd.WaitForExit();
if (!sd.HasExited)
{
sd.Close();
}
sd.Dispose();
r1 = null;
sd = null;
txtbackup.Clear();
txtbackup.AppendText("Backup is Finished");
}
its working fine ...but i want to store the backup.sql as a zip file in this path
#"C:\folder\Access\";
i have got this library Ionic.Zip.Reduced but i dont know how to zip the file and stored in the given path....

The library is pretty simple to use :
using (var zip = new ZipFile())
{
zip.AddFile("Backup.sql");
zip.Save(#"C:\folder\Access\"Backup.zip");
}
And even their homepage contains samples good enough for your use.

You should use this compression library or this one may be an option?

Related

Return network name from file path [duplicate]

This question already has answers here:
How do I determine a mapped drive's actual path?
(14 answers)
Closed 2 years ago.
I have ran into an issue where by when the user adds a file directory to my project the link is stored as their own mapped drive. For example;
C:\Location\Location
However, some users may have the C: drive on the server mapped as M: for example. Thus are unable to locate the file.
What I would like to do is replace this with the actual server name, ie
\\ArtServer\
I know that I could achieve this by replacing the opening part of the string, however if more servers are added in the future then this will obviously fallover in a huge mess. Currently the user grabs the file path using a standard get file dialogue;
public static string GetFilePath(string filter = "All Files (*.*)|*.*", string initialDirectory = #"This PC")
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = filter;
fileDialog.FilterIndex = 1;
fileDialog.Multiselect = false;
fileDialog.InitialDirectory = Directory.Exists(initialDirectory) ? initialDirectory : #"This PC";
if (fileDialog.ShowDialog() == true)
{
return fileDialog.FileName;
}
else
{
return null;
}
}
Is there anyway I can achieve this with what I currently have?
Thank you to #ADyson for all of your help. I decided to use an answer provided by ibram from the thread linked above. For anyone else who has the same issue I have posted what I had done;
public static string GetUNCPath(string path)
{
if (path.StartsWith(#"\\"))
{
return path;
}
ManagementObject mo = new ManagementObject();
mo.Path = new ManagementPath(String.Format("Win32_LogicalDisk='{0}'", path));
// DriveType 4 = Network Drive
if (Convert.ToUInt32(mo["DriveType"]) == 4)
{
return Convert.ToString(mo["ProviderName"]);
}
else
{
return path;
}
}
public static string GetFilePath(string filter = "All Files (*.*)|*.*", string initialDirectory = #"This PC")
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = filter;
fileDialog.FilterIndex = 1;
fileDialog.Multiselect = false;
fileDialog.InitialDirectory = Directory.Exists(initialDirectory) ? initialDirectory : #"This PC";
if (fileDialog.ShowDialog() == true)
{
// Split the file directory to gain root path
// Use GetUNCPath to convert root path to server name
string s = fileDialog.FileName;
int index = s.IndexOf(':') + 1;
string rootPath = GetUNCPath(s.Substring(0, index));
string directory = s.Substring(index);
return rootPath + directory;
}
else
{
return null;
}
}

How to write the username in a local txt file when login success and check on file for next login?

I want to create a local txt file and store username after login success and for next login the app will check on this file if the username exists for bypass login. But it seems like no file created when I testing it
bool bRet = ws.RequestMemberLogin(1, userName.Text, pass.Text, "", "");
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string filename = System.IO.Path.Combine(path, "user.txt");
FileInfo fi = new FileInfo(filename);
bool exist = fi.Exists;
if (bRet)
{
if (exist)
{
// Read
using (StreamReader streamReader = new StreamReader(filename))
{
string content = streamReader.ReadToEnd();
System.Diagnostics.Debug.WriteLine(content);
}
}
else
{
// Write
using (StreamWriter streamWriter = new StreamWriter(filename, true))
{
streamWriter.WriteLine(userName.Text);
}
}
Intent intent = new Intent(this, typeof(datalist));
StartActivity(intent);
}
else
{
error.Text = "Invalid username or password!";
}
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
the path will like
"/data/user/0/packagename/files/user.txt"
As you save it to Internal Storage,you couldn't see the files without root permission,if you want to view it,you could use adb tool (application signed by Android Debug)
adb shell
run-as packagename
cd /data/data/packagename
cd files
ls
then you could see the user.txt
or you could save it to External storage,then you could find it in your device File Manager:
//"/storage/emulated/0/Android/data/packagename/files/user.txt"
string path = Android.App.Application.Context.GetExternalFilesDir(null).ToString();

SSIS 2015 Script task convert text file to UTF8 in C# or VB

I want to convert my resulting txt file into a UTF8 formatted file so I can load it into my Azure SQL DW via Polybase. It is required the source file be in UTF8.
MSDN has an "IO Streaming example" HERE works perfectly for a single job. I am trying to architect an SSIS solution for around 30 tables though. I believe using this method would cause a race condition where the PS script will be locked by 1 SSIS package when another SSIS package needs it.
I am a sql dev, not a .NET dev so please forgive me. How would one convert the above to an SSIS C# Script task assuming I know how to pass parameters into the Script task?
PowerShell Code from MSDN
#Static variables
$ascii = [System.Text.Encoding]::ASCII
$utf16le = [System.Text.Encoding]::Unicode
$utf8 = [System.Text.Encoding]::UTF8
$ansi = [System.Text.Encoding]::Default
$append = $False
#Set source file path and file name
$src = [System.IO.Path]::Combine("<MySrcFolder>","<MyUtf8stage>.txt")
#Set source file encoding (using list above)
$src_enc = $ascii
#Set target file path and file name
$tgt = [System.IO.Path]::Combine("<MyDestFolder>","<MyFinalstage>.txt")
#Set target file encoding (using list above)
$tgt_enc = $utf8
$read = New-Object System.IO.StreamReader($src,$src_enc)
$write = New-Object System.IO.StreamWriter($tgt,$append,$tgt_enc)
while ($read.Peek() -ne -1)
{
$line = $read.ReadLine();
$write.WriteLine($line);
}
$read.Close()
$read.Dispose()
$write.Close()
$write.Dispose()
Update
I found a similar post which I was able to tweak to my needs, I swear I searched high and low before posting. Anyway here is what IS working for me. If you see anyway to improve it please share:
public void Main()
{
//$Package::SourceSQLObject = tablename
//$Package::StageFile_DestinationFolderPath = rootpath eg "C:\temp\"
string path = (string)Dts.Variables["$Package::StageFile_DestinationFolderPath"].Value;
string name = (string)Dts.Variables["$Package::SourceSQLObject"].Value;
string from = Path.Combine(path, name) + ".csv";
string to = Path.ChangeExtension(from, "txt");
Dts.Log("Starting " + to.ToUpper(), 0, null);
using (StreamReader reader = new StreamReader(from, Encoding.ASCII, false, 10))
using (StreamWriter writer = new StreamWriter(to, false, Encoding.UTF8, 10))
{
while (reader.Peek() >= 0)
{
writer.WriteLine(reader.ReadLine());
}
}
Dts.TaskResult = (int)ScriptResults.Success;
Your code indicates that your are trying to convert an ASCII file to UTF-8 however that article also states the following:
As UTF-8 uses the same character encoding as ASCII PolyBase will also
support loading data that is ASCII encoded.
So my advice to you is to try the file first with Polybase, check for any conversion issues before you spend any time trying to convert the files.
var mySrcFolder = ""; // something from user variables?
var myUtf8stage = ""; // something from user variables?
var myFinalstage = ""; // something from user variables?
// Static variables
var ascii = System.Text.Encoding.ASCII;
var utf16le = System.Text.Encoding.Unicode;
var utf8 = System.Text.Encoding.UTF8;
var ansi = System.Text.Encoding.Default;
var append = false;
// Set source file path and file name
var src = System.IO.Path.Combine(
mySrcFolder,
String.Format("{0}.txt", myUtf8stage));
// Set source file encoding (using list above)
var src_enc = ascii;
// Set target file path and file name
var tgt = System.IO.Path.Combine(
mySrcFolder,
String.Format("{0}.txt", myFinalstage));
// Set target file encoding (using list above)
var tgt_enc = utf8;
using (var read = new System.IO.StreamReader(src, src_enc))
using (var write = new System.IO.StreamWriter(tgt, append, tgt_enc))
{
while (read.Peek() != -1)
{
var line = read.ReadLine();
write.WriteLine(line);
}
}
public void Main()
{
//$Package::SourceSQLObject = tablename
//$Package::StageFile_DestinationFolderPath = rootpath eg "C:\temp\"
string path = (string)Dts.Variables["$Package::StageFile_DestinationFolderPath"].Value;
string name = (string)Dts.Variables["$Package::SourceSQLObject"].Value;
string from = Path.Combine(path, name) + ".csv";
string to = Path.ChangeExtension(from, "txt");
Dts.Log("Starting " + to.ToUpper(), 0, null);
using (StreamReader reader = new StreamReader(from, Encoding.ASCII, false, 10))
using (StreamWriter writer = new StreamWriter(to, false, Encoding.UTF8, 10))
{
while (reader.Peek() >= 0)
{
writer.WriteLine(reader.ReadLine());
}
}
Dts.TaskResult = (int)ScriptResults.Success;

C# Download the sound of a youtube video

I can download a video from youtube but I want the sound only. How can I do that?
Code I have for downloading the video (Using VideoLibrary):
YouTube youtube = YouTube.Default;
Video vid = youtube.GetVideo(txt_youtubeurl.Text);
System.IO.File.WriteAllBytes(source + vid.FullName, vid.GetBytes());
Install the NuGet packages: MediaToolkit and VideoLibrary, it will allow you to do the conversion by file extension.
var source = #"<your destination folder>";
var youtube = YouTube.Default;
var vid = youtube.GetVideo("<video url>");
File.WriteAllBytes(source + vid.FullName, vid.GetBytes());
var inputFile = new MediaFile { Filename = source + vid.FullName };
var outputFile = new MediaFile { Filename = $"{source + vid.FullName}.mp3" };
using (var engine = new Engine())
{
engine.GetMetadata(inputFile);
engine.Convert(inputFile, outputFile);
}
The above code works awesome you don't need to download the video first I created this procedure so when rookies like myself see this makes it easier to use.
You need the nuget packages MediaToolkit and VideoLibrary.
example url: https://www.youtube.com/watch?v=lzm5llVmR2E
example path just needs a path to save file to.
just add the name of the mp3 file to save
Hope this helps someone I have tested this code;
private void SaveMP3(string SaveToFolder, string VideoURL, string MP3Name)
{
var source = #SaveToFolder;
var youtube = YouTube.Default;
var vid = youtube.GetVideo(VideoURL);
File.WriteAllBytes(source + vid.FullName, vid.GetBytes());
var inputFile = new MediaFile { Filename = source + vid.FullName };
var outputFile = new MediaFile { Filename = $"{MP3Name}.mp3" };
using (var engine = new Engine())
{
engine.GetMetadata(inputFile);
engine.Convert(inputFile, outputFile);
}
}
based on this topic, i have developed a simple and dumb program to Download a youtube playlist. Hope this helps someone. It's just a Main.cs file: Youtube Playlist Downloader - Mp4 & Mp3
Ok found a better way the above code didn't normalize the audio posting it for others.
First Add Nuget package: https://www.nuget.org/packages/NReco.VideoConverter/
To Convert MP4 to MP3
// Client
var client = new YoutubeClient();
var videoId = NormalizeVideoId(txtFileURL.Text);
var video = await client.GetVideoAsync(videoId);
var streamInfoSet = await client.GetVideoMediaStreamInfosAsync(videoId);
// Get the best muxed stream
var streamInfo = streamInfoSet.Muxed.WithHighestVideoQuality();
// Compose file name, based on metadata
var fileExtension = streamInfo.Container.GetFileExtension();
var fileName = $"{video.Title}.{fileExtension}";
// Replace illegal characters in file name
fileName = RemoveIllegalFileNameChars(fileName);
tmrVideo.Enabled = true;
// Download video
txtMessages.Text = "Downloading Video please wait ... ";
//using (var progress = new ProgressBar())
await client.DownloadMediaStreamAsync(streamInfo, fileName);
// Add Nuget package: https://www.nuget.org/packages/NReco.VideoConverter/ To Convert MP4 to MP3
if (ckbAudioOnly.Checked)
{
var Convert = new NReco.VideoConverter.FFMpegConverter();
String SaveMP3File = MP3FolderPath + fileName.Replace(".mp4", ".mp3");
Convert.ConvertMedia(fileName, SaveMP3File, "mp3");
//Delete the MP4 file after conversion
File.Delete(fileName);
LoadMP3Files();
txtMessages.Text = "File Converted to MP3";
tmrVideo.Enabled = false;
txtMessages.BackColor = Color.White;
if (ckbAutoPlay.Checked) { PlayFile(SaveMP3File); }
return;
}
I like the idea of using a method. I tried SaveMP3() but it had some problems.
This worked for me: `
private void SaveMP3(string SaveToFolder, string VideoURL, string MP3Name)
{
string source = SaveToFolder;
var youtube = YouTube.Default;
var vid = youtube.GetVideo(VideoURL);
string videopath = Path.Combine(source, vid.FullName);
File.WriteAllBytes(videopath, vid.GetBytes());
var inputFile = new MediaFile { Filename = Path.Combine(source, vid.FullName) };
var outputFile = new MediaFile { Filename = Path.Combine(source , $"{MP3Name}.mp3") };
using (var engine = new Engine())
{
engine.GetMetadata(inputFile);
engine.Convert(inputFile, outputFile);
}
File.Delete(Path.Combine(source, vid.FullName));
}
`

how to make rar file of full folder using c#

I have a procedure for making .rar file.
Code
public static void RarFilesT(string rarPackagePath, Dictionary<int, string> accFiles)
{
string[] files = new string[accFiles.Count];
int i = 0;
foreach (var fList_item in accFiles)
{
files[i] = "\"" + fList_item.Value;
i++;
}
string fileList = string.Join("\" ", files);
fileList += "\"";
System.Diagnostics.ProcessStartInfo sdp = new System.Diagnostics.ProcessStartInfo();
string cmdArgs = string.Format("A {0} {1} -ep",
String.Format("\"{0}\"", rarPackagePath),
fileList);
sdp.ErrorDialog = true;
sdp.UseShellExecute = true;
sdp.Arguments = cmdArgs;
sdp.FileName = rarPath;//Winrar.exe path
sdp.CreateNoWindow = false;
sdp.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(sdp);
process.WaitForExit();
}
This producer needs an string array of file list for making rar file.
Can any one tell me how can i make rar of a complete folder with sub folders and files.
Sorry 1 mistake and i also need selected extension files from given folder.
Updated function
/// <summary>
/// Package files. (Build Rar File)
/// </summary>
/// <param name="rarPackagePath">Rar File Path</param>
/// <param name="accFiles">List Of Files To be Package</param>
public static string RarFiles(string rarPackagePath,
Dictionary<int, string> accFiles)
{
string error = "";
try
{
string[] files = new string[accFiles.Count];
int i = 0;
foreach (var fList_item in accFiles)
{
files[i] = "\"" + fList_item.Value;
i++;
}
string fileList = string.Join("\" ", files);
fileList += "\"";
System.Diagnostics.ProcessStartInfo sdp = new System.Diagnostics.ProcessStartInfo();
string cmdArgs = string.Format("A {0} {1} -ep1 -r",
String.Format("\"{0}\"", rarPackagePath),
fileList);
sdp.ErrorDialog = false;
sdp.UseShellExecute = true;
sdp.Arguments = cmdArgs;
sdp.FileName = winrarPath;//Winrar.exe path
sdp.CreateNoWindow = false;
sdp.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(sdp);
process.WaitForExit();
error = "OK";
}
catch (Exception ex)
{
error = ex.Message;
}
return error;
}
For this u can make rar with full folder path.
-r argument can recursive folder and files.
Thanks to bystander.
And also u can specify extension for packaging.
Ex.
string rarPackage = "E:/Backup.rar";
Dictionary<int, string> accFiles = new Dictionary<int, string>();
accFiles.Add(1, "D://*.txt");
accFiles.Add(2, "D://*.html");
accFiles.Add(3, "D://*.jpg");
RarFiles(rarPackage, accFiles);
Un-Rar
public static void UnrarFiles(string rarPackagePath, string dir)
{
System.Diagnostics.ProcessStartInfo sdp = new System.Diagnostics.ProcessStartInfo();
string cmdArgs = string.Format("X {0} * {1}",
String.Format("\"{0}\"", rarPackagePath),
String.Format("\"{0}\"", dir));
sdp.Arguments = cmdArgs;
sdp.ErrorDialog = true;
sdp.UseShellExecute = true;
sdp.CreateNoWindow = false;
sdp.FileName = rarPath;
sdp.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(sdp);
process.WaitForExit();
}
-r argument can recursive folder and files..
so you add "-r" to
string cmdArgs = string.Format("A {0} {1} -ep -r",
String.Format("\"{0}\"", rarPackagePath),
fileList);
Ashish, Thanks for posting this; it's very helpful to me, as I've been told at the last moment that some files I have to FTP are supposed to be RARed first.
But I'm curious -- why is accFiles a dictionary, rather than a string[] or a Collection? Microsoft suggests not to pass dictionaries in public APIs: http://msdn.microsoft.com/en-us/library/dn169389(v=vs.110).aspx
Also, using a StringBuilder would clean up building fileList. I'd suggest this:
public static string RarFiles(string rarPackagePath,
Collection<string> accFiles)
{
string error = "";
try
{
StringBuilder fileListBuilder = new StringBuilder();
foreach (var fList_item in accFiles)
{
fileListBuilder.Append("\"" + fList_item + "\" ");
}
string fileList = fileListBuilder.ToString();
... (no change from this point on)
}
Again, thanks -- it's really been very helpful to me. I hope my suggestions are helpful to you, as well.

Categories