Extract All gz files inside a folder in C# - c#

I am working on a application and need to extract the gz files inside a folder.
what I need is a c# script that can loop all gz files in a given folder and extract them into the same folder.
I know there are some libraries for this, But I could not able to get them work for gz, I got them working for zip though.
Or if there are any other solution for the same i.e if batch script can be created that can use WinRar command line utility to achieve the same. I don't know just an Idea if possible.
Note: I think I have to drop that second option- WinRar command is able to handle only RAR files.
Thanks

Try this as a batch file with winrar's "unrar" commandline freeware:
#REM ------- BEGIN demo.cmd ----------------
#setlocal
#echo off
set path="C:\Program Files\WinRAR\";%path%
for /F %%i in ('dir /s/b *.gz') do call :do_extract "%%i"
goto :eof
:do_extract
echo %1
mkdir %~1.extracted
pushd %~1.extracted
unrar e %1
popd
REM ------- END demo.cmd ------------------
Courtesy of: http://www.respower.com/page_tutorial_unrar

I can suggest something like below:
using System;
using System.IO;
using System.Linq;
class Program
{
static void Main(string[] args)
{
try
{
var files = from file in Directory.EnumerateFiles(#"c:\something",
"*.gz", SearchOption.AllDirectories)
select new
{
File = file,
};
foreach (var f in files)
{
Process.Start("c:\winrar.exe", f.File);
}
Console.WriteLine("{0} files found and extracted!",
files.Count().ToString());
}
catch (UnauthorizedAccessException UAEx)
{
Console.WriteLine(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
Console.WriteLine(PathEx.Message);
}
}
}
NOTE: Please replace paths and winrar.exe parameters yourself with
correct one.

I got it solved. Thanks MichelZ for showing the way to go. I got the 7-zip command line version to done the trick for me.
#REM ------- BEGIN demo.cmd ----------------
#setlocal
#echo off
set path="C:\Program Files\7-Zip\";%path%
for /F %%i in ('dir /s/b *.gz') do call :do_extract "%%i"
for /F %%i in ('dir /s/b *.zip') do call :do_extract "%%i"
goto :eof
:do_extract
pushd %~dp1
7z e %1 -y
popd
REM ------- END demo.cmd ------------------

#setlocal
#echo off
set path="C:\Program Files\WinRAR\";%path%
for /F %%i in ('dir /s/b *.gz') do call :do_extract "%%i"
goto :eof
:do_extract
echo %1
mkdir %~1.extracted
pushd %~1.extracted
Winrar e %1
popd

Related

C# Register a dll driver programmatically while runtime

Sorry if it's a duplicate question, but I couldn't find an answer.
I'm writing a program for store scales. The driver of the scales is available in .dll format. I'm using the program by referring to the driver in this .dll. Now I register .dll via CMD. So I need to register .dll while runtime or installing application. But I couldn’t set it up either by reference or by code.
Now I'm registering it up as follows.
c: [Enter]
cd \RongtaScales [Enter]
C:\Windows\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe file.dll [Enter]
It works this way, but customers can’t always register it that way. I need to register it along with the program.
I tried the following:
try
{
Assembly asm = Assembly.LoadFile(#"E:\rtscaledrv.dll");
RegistrationServices regAsm = new RegistrationServices();
bool bResult = regAsm.RegisterAssembly(asm, AssemblyRegistrationFlags.SetCodeBase);
MessageBox.Show("Installed: '"+ bResult.ToString() + "'");
}
catch (Exception exs)
{
MessageBox.Show("Error: '"+ exs.ToString() +"'");
//throw;
}
This returned an error as follows:
If I try to add via Referenceses it returns the following error:
My question is, how can I register a .dll together while the program is running or installing? I can't find the exact answer from google right now.
Thanks!
UPDATED
If I try with batch file it also doesn't work:
#echo off
setlocal
set "RegSvr32=%SystemRoot%\System32\regsvr32.exe"
set "RegAsm=%SystemRoot%\Microsoft.NET\Framework\v2.0.50727\RegAsm.exe"
if not exist "%RegAsm%" set "RegAsm=%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe"
if not exist "%RegAsm%" set "RegAsm=%SystemRoot%\Microsoft.NET\Framework\v1.1.4322\RegAsm.exe"
rem Make note of any files which cause an exception to be thrown.
for /f "delims=" %%A in ('dir a-d /b *.dll *.ocx') do "%RegSvr32%" /s "%%~fA" && echo %%~nA SVR Registered || "%RegAsm%" /nologo /silent "%%~fA" 2>nul && echo %%~nA ASM Registered || echo %%~nA Skipped
endlocal
#pause /b 0
It returned:
rtscaledrv Skipped
Press any key to continue . . .

How to search for specific word in xml file in windows command

I have following content in my file:
<?xml version="1.0" encoding="utf-8"?>
<Include>
<?define MajorVersion = "2" ?>
<?define MinorVersion = "5" ?>
<?define BuildNumber = "64" ?>
<?define RevisionNumber = "0" ?>
<?define FullVersion = "$(var.MajorVersion).$(var.MinorVersion).$(var.BuildNumber).$(var.RevisionNumber)"?>
</Include>
I want to read this file during PostBuild or AfterBuild event in c#. As access to windows commands are available during this event, I am trying to use cmd to read variables value defined in it i.e. value of "MajorVersion", "MinorVersion", "BuildNumber" and "RevisionNumber". Then I will run the command to rename a folder using these variables. How could I read those specific values in cmd prompt/batch?
For the file content I posted above, I want folder to be renamed to "2.5.64.0".
I looked into this solution - Read XML file with windows batch
In the above link, value is present between two nodes but in my case values are present as attribute's value.
I used following commands in batch file to achieve the required output:
#echo off
setlocal enableextensions disabledelayedexpansion
set "MajorVersion="
set "MinorVersion="
set "BuildNumber="
set "RevisionNumber="
for /f "tokens=4 delims= " %%a in ('findstr /c:"MajorVersion =" xmlFile.xml') do set "MajorVersion=%%a"
for /f "tokens=4 delims= " %%a in ('findstr /c:"MinorVersion =" xmlFile.xml') do set "MinorVersion=%%a"
for /f "tokens=4 delims= " %%a in ('findstr /c:"BuildNumber =" xmlFile.xml') do set "BuildNumber=%%a"
for /f "tokens=4 delims= " %%a in ('findstr /c:"RevisionNumber =" xmlFile.xml') do set "RevisionNumber=%%a"
echo %MajorVersion%
echo %MinorVersion%
echo %BuildNumber%
echo %RevisionNumber%"
set "FullVersion=%MajorVersion%.%MinorVersion%.%BuildNumber%.%RevisionNumber%"
echo %FullVersion%
rename "OldFolderName" %FullVersion%
As far as I can tell, you can't read a file into a variable in a VS post-build event.
However, you can run an external batch file and provide it with arguments. You can trigger this batch file and have batch file read xml file and create required folder:
CD "$(ProjectDir)"
IF EXIST postBuild.bat (
#ECHO Post-build script exists at: $(ProjectDir)postBuild.bat - executing...
CALL "$(ProjectDir)postBuild.bat" "$(XmlFilePath)"
)
The batch file postBuild.bat in the project dir then looks something like this:
#REM **********
#REM Post-build script; assumes params:
#REM postBuild.bat "$( XmlFilePath)"
#REM **********
#ECHO XmlFilePath: %1
[...]

Execute CMD commands in C#

Well, before actually asking the question, I'll give you guys a brief description of what I'm trying to do. I wrote a few batches to install stuff here, and they work pretty well. The thing is... I want to write a program in C# that does the same thing as the batches. Most of what the batches do is call up files and fire them with parameters like /S or /silent. And, of course, activate Windows/Office.
But I'm having problems running the Office/Windows activators. Below, you'll see the sctructure of the batches we use and the C# program's structure as well.
#echo off
::Office Installation
:AskOffice
set INPUT=
set /P INPUT=Do you want to install Office 2010 (1), Office 2013 (2) or skip this step (3)? %=%
If /I "%INPUT%"=="1" goto 1
If /I "%INPUT%"=="2" goto 2
If /I "%INPUT%"=="3" goto eof
echo.
echo Invalid input & goto AskOffice
::Office 2010
:1
set INPUT=
set /P INPUT=Do you want to install Office (1) or just activate it (2)?
If /I "%INPUT%"=="1" goto instalar2010
If /I "%INPUT%"=="2" goto windows2010
:instalar2010
echo Installing Office 2010...
"\\jamaica\sistemas$\INSTALL\~SOFTWARES\Office\Office 2010\setup.exe" /config "\\jamaica\sistemas$\INSTALL\~SOFTWARES\Office\Office 2010\ProPlus.WW\config.xml"
goto windows2010
:windows2010
if defined ProgramFiles(x86) (
#echo You're running a x64 system...
goto 2010x64
) else (
#echo You're running a x86 system...
goto 2010x86
)
:2010x86
::Office 2010 Activation (x86)
echo Activating Office 2010 (x86)...
c:\windows\system32\cscript "C:\Program Files\Microsoft Office\Office14\OSPP.VBS" /inpkey:XXXXXXXXX
c:\windows\system32\cscript "C:\Program Files\Microsoft Office\Office14\OSPP.VBS" /act
goto eof
:2010x64
::Office 2010 Activation (x64)
echo Activating Office 2010 (x64)...
c:\windows\system32\cscript "C:\Program Files (x86)\Microsoft Office\Office14\OSPP.VBS" /inpkey:XXXXXXX
c:\windows\system32\cscript "C:\Program Files (x86)\Microsoft Office\Office14\OSPP.VBS" /act
goto eof
::Office 2013
:2
set INPUT=
set /P INPUT=Do you want to install Office (1) or just activate it (2)?
If /I "%INPUT%"=="1" goto instalar2013
If /I "%INPUT%"=="2" goto windows2013
:instalar2013
echo Installing Office 2013...
"\\jamaica\sistemas$\Install\~SOFTWARES\Office\Office 2013\setup.exe" /config "\\jamaica\sistemas$\Install\~SOFTWARES\Office\Office 2013\proplus.ww\config.xml"
goto windows2013
:windows2013
if defined ProgramFiles(x86) (
#echo You're running a x64 system...
goto 2013x64
) else (
#echo You're running a x86 system...
goto 2013x86
)
:2013x86
::Office 2013 Activation (x86)
echo Activating Office 2013...
c:\windows\system32\cscript "C:\Program Files\Microsoft Office\Office15\OSPP.VBS" /inpkey:XXX
c:\windows\system32\cscript "C:\Program Files\Microsoft Office\Office15\OSPP.VBS" /act
goto eof
:2013x64
::Office 2013 Activation (x64)
echo Activating Office 2013...
c:\windows\system32\cscript "C:\Program Files (x86)\Microsoft Office\Office15\OSPP.VBS" /inpkey:XXXX
c:\windows\system32\cscript "C:\Program Files (x86)\Microsoft Office\Office15\OSPP.VBS" /act
goto eof
:eof
This is my batch's code. All it does is ask which version of Office you'd like to install and then it activates it. Or, you can just activate it if you want. I want to do the same thing with C#, but using only C#. I could just create a method to fire up the batch file, but, well... I want to learn how to make CMD commands work in C#. Here's my C# class' code.
/* Office's installers' paths */
string varCaminhoOffice2010 = #"\\romenia\install$\~SOFTWARES\Office\Office 2010\setup.exe";
string varCaminhoOffice2013 = #"\\romenia\install$\~SOFTWARES\Office\Office 2013\setup.exe";
/* Local folders */
string varCaminhoOffice2010x86 = #"C:\Program Files\Microsoft Office\Office14\OSPP.VBS";
string varCaminhoOffice2010x64 = #"C:\Program Files (x86)\Microsoft Office\Office14\OSPP.VBS";
string varCaminhoOffice2013x86 = #"C:\Program Files\Microsoft Office\Office15\OSPP.VBS";
string varCaminhoOffice2013x64 = #"C:\Program Files (x86)\Microsoft Office\Office15\OSPP.VBS";
/* Methods */
public void mtdAtivaOffice2010()
{
/* Office Activation */
if (mtdCheckArc == false) // Checking system's architecture
{
// x86
System.Diagnostics.Process.Start("CMD.exe", "/C %systemroot%\system32\cscript" + varCaminhoOffice2010x86 + "/inpkey:XXXX");
System.Diagnostics.Process.Start("CMD.exe", "/C %systemroot%\system32\cscript" + varCaminhoOffice2010x86 + "/act");
}
else
{
// x64
System.Diagnostics.Process.Start("CMD.exe", "/C %systemroot%\system32\cscript" + varCaminhoOffice2010x64 + "/inpkey:XXXX");
System.Diagnostics.Process.Start("CMD.exe", "/C %systemroot%\system32\cscript" + varCaminhoOffice2010x64 + "/act");
}
}
public void mtdAtivaOffice2013()
{
/* Office activation */
if (mtdCheckArc == false) // Checking system's architecture
{
// x86
System.Diagnostics.Process.Start("CMD.exe", "/C %systemroot%\system32\cscript" + varCaminhoOffice2013x86 + "/inpkey:XXXX");
System.Diagnostics.Process.Start("CMD.exe", "/C %systemroot%\system32\cscript" + varCaminhoOffice2013x86 + "/act");
}
else
{
// x64
System.Diagnostics.Process.Start("CMD.exe", "/C %systemroot%\system32\cscript" + varCaminhoOffice2013x64 + "/inpkey:XXXX");
System.Diagnostics.Process.Start("CMD.exe", "/C %systemroot%\system32\cscript" + varCaminhoOffice2013x64 + "/act");
}
}
Everytime I try to run the project, Visual Studio gives me compilation error messages. I've tried a few things, and tried search the forums for help, but nothing helped me. I tried also:
Tried setting each command as a variable and then making the method run them:
string varCScript = #"%systemroot%\system32\cscript";
string varSerial2010 = "/inpkey:XXXX";
string varSerial2013 = "/inpkey:XXXX";
string varActivate = "/act";
System.Diagnostics.Process.Start("CMD.exe", "/C" + varCScript + varCaminhoOffice2010x86 + varSerial2010);
System.Diagnostics.Process.Start("CMD.exe", "/C" + varCScript + varCaminhoOffice2010x64 + varSerial2010);
System.Diagnostics.Process.Start("CMD.exe", "/C" + varCScript + varCaminhoOffice2013x86 + varSerial2013);
System.Diagnostics.Process.Start("CMD.exe", "/C" + varCScript + varCaminhoOffice2013x64 + varSerial2013);
Tried also inserting the wole command as a single string:
string varCommand = "%systemroot%\system32\cscript \"C:\Program Files (x86)\Microsoft Office\Office15\OSPP.VBS\" /inpkey:XXXX";
I also tried adding more "\"s to this last line of code, between folders. Like "C:\\windows\\system32", but nothing works. Sometimes I get compilation erros, and sometimes my program runs... but when the CMD window opens, it flashes for a second and disappears. All I could read from one of them was "syntax problem". So, well... it looks like CMD isn't reading my strings properly. I mean, I'm not declaring them properly.
Could you guys help me with this one?
You need spaces between your parameters, and quotes around parameters which have spaces.
Also, to get some more info: put a breakpoint on the Process.Start line, get the script & arguments, and paste them into a cmd window.

Script to close program that's causing CPU overheat

You see i use CoreTemp program to monitor CPU heat, this program allows you to run a script or a program when the CPU temp reaches a specified value..
What i want is that when the CPU temp reaches a certain value, the process that has the most CPU usage is to be closed!!
In other words, I need a Script/program that automatically scans the processes and force close the process that has the highest CPU usage..
Thanks!
Try this :
Check the prog with the higher Memory Use :
#echo off
setlocal EnableDelayedExpansion
for /f "skip=4 tokens=1-5 delims= " %%a in ('tasklist') do (
set $Size=00000000%%e
set $Size=!$size:.=!
set #!$size:~-10!=%%a
)
for /f "tokens=2 delims==" %%a in ('set #') do (set $Bigger=%%a)
echo taskkill /IM !$Bigger!
Check the process with the higher CPU use :
#echo off
setlocal EnableDelayedExpansion
for /f "skip=2 tokens=1-2 delims= " %%a in ('"wmic path Win32_PerfFormattedData_PerfProc_Process get Name,PercentProcessorTime"') do (
if "%%a"=="_Total" goto:next
set #%%b=%%a
)
:next
for /f "tokens=1-2 delims==" %%a in ('set #') do (
set $Bigger=%%b
set $Value=%%a
)
if "!$Value!"=="#0" goto:nothing
echo taskkill /IM !$Bigger!.exe [!$Value:#=!%%]
goto:eof
:nothing
Echo CPU IS INACTIVE
If the output is OK for you remove the ECHO on the last line
You can ameliorate the script. In case you have two processus with the same name you have to work with th PID of the process in place of the name. Because the programm will return program#1, program#2, etc.. That's just the base script.
And Like #09stephenb commented you have to go carrefully with such a script....
I started working on this for you but I have to leave. It's mostly complete so I'm just gonna give you what I have so far and let you take it from there.
#echo off
setlocal
set proc=Win32_PerfFormattedData_PerfProc_Process
set "wmi=wmic path %proc% get Name^,PercentProcessorTime"
for /f "skip=1 tokens=*" %%a in ('"%wmi%"^|findstr /i /v /g:Excludes.txt') do (
for /f "tokens=2 delims= " %%b in ( "%%a" ) do if %%b NEQ 0 echo %%a
)
Create a file called Excludes.txt and make sure it's in the same dir of your script.
"System Idle Process"
Idle
explorer.exe
taskmgr.exe
lsass.exe
csrss.exe
smss.exe
winlogon.exe
svchost.exe
services.exe
Core Temp
_Total

Batch to copy files to another folder with breaks

I need a script, prefferably a windows batch or C# to do as following:
Show a prompt that first ask for the source folder,
then it should ask for the destination folder. At last, it shall ask how many files it should copy to the destination, from the source.
// We talk about aprox 100.000 files and they can be moved in random order.
After the process has been run, the program shall make a break of 10 minutes, then loop the process it was told to earlier, by previous answers to the prompt.
I've tried a little, but haven't found a solution. As far as i can see, XCOPY is unable to work around all these criterias.
Thanks in advance,
Mark
RoboCopy (the See also section might interest you as well) or
(more recent:) RichCopy (download)
You can use something like this:
string source = Console.ReadLine();
string destination = Console.ReadLine();
int numberOfFilesToCopy = int.Parse(Console.ReadLine());
DirectoryInfo di = new DirectoryInfo(source);
var files = di.GetFiles();
for(i=0;i < math.Max(files.Length, numberOfFilesToCopy);i++)
{
files[i].CopyTo(destination);
}
In C# using System.IO.File.Copy(sourceFileName,destFileName) followed by a System.IO.File.Delete(path) will do the "move" for you. You can create a simple console app that takes in the information you need and then does the work.
Have a look at the docs for System.IO.File for more info on File operations.
I'm not sure this fulfills all your requirements, but it may be useful to have a look at robocopy (robocopy /? in the command line).
Don't think I missed anything =D
#ECHO OFF
::User Prompts
SET /p source=Source Folder? Use format DRIVE:\PATH\ :
SET /p destination=Destination Folder? Use format DRIVE:\PATH\ :
SET /p count=How many files to copy? :
::Setup the Batch file to schedule
DIR /B "%source%">>"%userprofile%\batchtemp\source.BAT"
SET batchfile=%userprofile%\batchtemp\source.BAT
ECHO SETLOCAL ENABLEDELAYEDEXPANSION>>"%batchfile%"
ECHO FOR /F "USEBACKQ tokens=*" %%A IN ("%batchfile%") DO ( >>"%batchfile%"
ECHO COPY /Y "%%~fA" "%destination%\%%~nxA">>"%batchfile%"
ECHO SET /a count=!count!-1>>"%batchfile%"
ECHO IF %count% EQU 0 GOTO CLEANUP>>"%batchfile%"
ECHO )>>"%batchfile%"
ECHO :CLEANUP>>"%batchfile%"
ECHO ENDLOCAL>>"%batchfile%"
::Setup the scheduled task based on a future time in minutes.
REM Given that the job will run on the same day not overlapping a 24 hour day
FOR /F "tokens=1-3 delims=: " %%F IN ('time /t') DO (
SET hours=%%F
SET minutes=%%G
)
FOR /F "tokens=1-4 delims=/ " %%F IN ('date /t') DO (
SET day=%%F
SET thedate=%%G/%%H/%%I
)
SET /a minutes=%minutes%+10
IF %minutes% GRT 60 SET /a minutes=%minutes%-60 & SET /a hours=%hours%+1
SCHTASKS /Create /TR "%batchfile%" /ST %hours%:%minutes%:00 /MO ONCE /D %day% /SD "%thedate%" /ED "%thedate%" /TN "Copy Files"

Categories

Resources