Remove file present on Linux server - c#

Trying to run sudo command with user who has all the priviledges, but something is wrong in my code .
I am trying to remove a file present on the remote server via C# code. It says : The name 'pass' does not exist in the current context.:
My Code :
SshExec sshExec = new SshExec("sj1slm612", "karansha");
sshExec.Password = "pass";
sshExec.Connect();
//Removing config files from sj1slm612 server
string remove_config_file_express = "echo " + "'" + pass + "'" + "| sudo -S -u wtsnqa rm " + "/apps/instances/express_13000/configuration/standalone-full.xml";
string output_express = sshExec.RunCommand(remove_config_file_express);
Console.WriteLine("All config files removed");
Console.ReadLine();

the compiler is indeed correct. you reference a variable called pass which you probably meant to be the string "pass"
string remove_config_file_express = "echo " + "'" + pass + "'" + "| sudo -S -u wtsnqa rm " + "/apps/instances/express_13000/configuration/standalone-full.xml";

Use tamir Library next code.
public static bool BorrarArchivo(string rutaRemota)
{
try
{
SshExec comando = new SshExec(Servidor, Usuario);
comando.Password = Password;
comando.Connect();
string paso = comando.RunCommand("rm " + rutaRemota);
comando.Close();
return true;
}
catch (Exception ex)
{
mErrorSFTP = ex.Message;
return false;
}
}

Related

"sqlcmd.exe -S Instance USE ..." work in command line, but I can't move it to c # process

I am trying move this command to C# Process:
SQLCMD.EXE -S InstanceName
USE [master]
GO
CREATE DATABASE [Ek] ON
( FILENAME = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\Ek_Primary.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL
Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\Ek_Primary.ldf' )
FOR ATTACH ;
GO
EXIT
I have:
try
{
Process p = CreateProcess();
p.StartInfo.FileName = #"C:\Program Files\Microsoft SQL Server\Client SDK\ODBC\170\Tools\Binn\SQLCMD.EXE";
p.StartInfo.Arguments = "-S InstanceName" + "\n" +
"USE [master]" + "\n" +
"GO" + "\n" +
"CREATE DATABASE [Ek] ON" + "\n" +
"( FILENAME = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL15.MSSQLSERVER\\MSSQL\\DATA\\Ek_Primary.mdf' )," + "\n" +
"( FILENAME = N'C:\\Program Files\\Microsoft SQL Server\\MSSQL15.MSSQLSERVER\\MSSQL\\DATA\\Ek_Primary.ldf' )" + "\n" +
"FOR ATTACH ;" + "\n" +
"GO" + "\n" +
"EXIT" + "\n";
Console.WriteLine(p.StartInfo.Arguments);
p.Start();
var output = p.StandardOutput.ReadToEnd();
var err = p.StandardError.ReadToEnd();
Console.WriteLine("O: " + output);
Console.WriteLine("E: " + err);
}
catch (Exception e) { Console.WriteLine(e.Message); ; }
It return err = Unexpected argument. Enter '-?' for help.
I was trying set FileName on cmd.exe and move path to Arguments. But it waits forever for a response and does not exit p.StandardOutput.ReadToEnd ();
I was trying send each line of code individually, but also without success.
And I trying with /C on start p.StartInfo.Argument but it does not change anything.
Thanks to Selvin suggestion. I made it by:
string sqlConnectionString = #"Integrated Security=SSPI;Persist Security Info=False;Data Source=InstanceName";
string script = File.ReadAllText(#"../../sql.sql");
Microsoft.Data.SqlClient.SqlConnection conn = new Microsoft.Data.SqlClient.SqlConnection(sqlConnectionString);
Server server = new Server(new ServerConnection(conn));
server.ConnectionContext.ExecuteNonQuery(script);
where in sql.sql I added all my sql line.

Value assigned more than once in single assignment

I made script task that's downloading and saving on disk two spreadsheets from Google Drive using file ID and prepared URL address.
This is main() from my C# code, there are no things outside of it:
public void Main()
{
string m_FileId = Dts.Variables["User::varFileId"].Value.ToString();
string m_RemoteUrl = "https://docs.google.com/spreadsheets/d/" + m_FileId + "/export?format=xlsx";
string m_FilePath = null;
WebClient client = new WebClient();
try
{
m_FilePath = Dts.Variables["User::varFilePath"].Value.ToString() + Dts.Variables["User::varFileName"].Value.ToString();
client.DownloadFile(new System.Uri(m_RemoteUrl), m_FilePath);
m_FilePath = "";
m_FileId = Dts.Variables["User::varFileId2"].Value.ToString();
m_RemoteUrl = "https://docs.google.com/spreadsheets/d/" + m_FileId + "/export?format=xlsx";
m_FilePath = Dts.Variables["User::varFilePath"].Value.ToString() + Dts.Variables["User::varFileName2"].Value.ToString();
client.DownloadFile(new System.Uri(m_RemoteUrl), m_FilePath);
}
catch(Exception e)
{
Dts.Events.FireError(0, "FileDownload", e.Message
+ "\r" + e.StackTrace
+ " \rUrl: " + m_RemoteUrl
+ " \rFilePath: " + m_FilePath
+ " \rPath: " + Dts.Variables["User::varFilePath"].Value.ToString()
+ " \rFileName2: " + Dts.Variables["User::varFileName2"].Value.ToString()
, string.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
Dts.TaskResult = (int)ScriptResults.Success;
}
Problem occurs exactly on every second time I run this code and I don't know how to get rid of it. There's just exception in my script task. I'm printing all variables that are used in this code, and as you can see there's something wrong with m_FilePath, it's like multiplied despite of being printed just once.
[FileDownload] Error: An exception occurred during a WebClient request.
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at ST_84b63d1593dd449886eb2b32dff40b2d.ScriptMain.Main()
Url: https://docs.google.com/spreadsheets/d/----------/export?format=xlsx
FilePath: C:\Google Drive extract\ga_manual_cost_file.xlsxC:\Google Drive extract\ga_manual_cost_file.xlsx
Path: C:\Google Drive extract\ga_manual_cost_file.xlsx
FileName2: ga_manual_cost_file.xlsx
SSIS variables that I'm using are ReadOnly, and are used only in this script task(I tried running only this part of control flow), and their values are as follows:

C# - Executing external exectutable with arguments

I have been trying to convert my python code to c# code. For some reason, the c# code gets to the DirectoryInfo declaration and says the path is not found. If someone can tell me why, it would be appreciated.
This is the original python code:
def encode(path, dest):
for root_dir, dirs, files in os.walk(path, topdown=False):
for name in files:
(base, ext)=os.path.splitext(name)
input_file = os.path.join(root_dir,name)
output_file = os.path.join(dest_dir, base+".mkv")
if (os.path.exists(output_file)):
print ("skipped")
else:
subprocess.call( ["HandBrakeCLI.exe", "-i", input_file, "-o", output_file, "-e", "x264", "--aencoder", "ac3", "-s", "1", "--subtitle-default", "1" ])
This is my current c# code:
string qpath = Path.GetFullPath((Environment.CurrentDirectory + "\\Queue\\"));
if (Directory.Exists(Path.GetFullPath(qpath)))
{
var DirMKV = (Directory.GetFiles(qpath, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".mkv") || s.EndsWith(".mp4")).ToArray());
foreach (string file in DirMKV)
{
DirectoryInfo dirinfo = new DirectoryInfo(file);
if (dirinfo.Parent.Parent.ToString().Contains("S"))
{
string ipath = Environment.CurrentDirectory;
string dpath = ipath + #"\Queue\" + dirinfo.Parent.Parent.ToString() + #"\" + Path.GetFileName(file);
string opath = ipath + #"\Finished\" + dirinfo.Parent.Parent.ToString() + #"\" + Path.GetFileName(file);
string arg = "-i " +dpath + " -o " +opath +" -e x264 "+ " --aencoder ac3 "+ "-s 1 "+ "--subtitle-default 1";
if (!File.Exists(opath))
{
Process.Start(ipath + #"\handbrakeCLI.exe", arg);
}
}
}
}
I don't understand Python, but from what I see, your c# code and python code definitely do different things. There are bunch of things that are not clear. I have commented your code with my advice. Hopefully that will solve your issues
Commented code below
string qpath = Path.GetFullPath((Environment.CurrentDirectory + "\\Queue\\"));
if (Directory.Exists(Path.GetFullPath(qpath))) // No need to do Path.GetFullPath again
{
var DirMKV = (Directory.GetFiles(qpath, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".mkv") || s.EndsWith(".mp4")).ToArray()); // no need to do ToArray. List all files in Queue folder
foreach (string file in DirMKV)
{
DirectoryInfo dirinfo = new DirectoryInfo(file); // I don't get any Path not found exception here
if (dirinfo.Parent.Parent.ToString().Contains("S")) // Check if GrandParent directory name contains the letter S. Don't see any such thing in python code
{
string ipath = Environment.CurrentDirectory;
string dpath = ipath + #"\\Queue\\" + dirinfo.Parent.Parent.ToString() + #"\" + Path.GetFileName(file); // Set input file to something like Queue\*S*\File.mkv. Does this file exist??? It should use single backslash instead of double backslash
string opath = ipath + #"\\Finished\\" + dirinfo.Parent.Parent.ToString() + #"\" + Path.GetFileName(file); // Set output file to something like Finished\*S*\File.mkv. It should use single backslash instead of double backslash
string arg = "-i " +dpath + " -o " +opath +" -e x264 "+ " --aencoder ac3 "+ "-s 1 "+ "--subtitle-default 1";
if (!File.Exists(opath))
{
Process.Start(ipath + #"\handbrakeCLI.exe", arg); // does the handbrakeCLI.exe exist in the current directory????
}
}
}
}
Below code is based on my guess about what you want
/*
* Expects a directory structure like below
* S
* |-> bin
* |-> Queue
* |-> test1.mp4
* |-> test2.mkv
* |-> Finished
* |-> test3.mkv
* |-> executable (this code)
* |-> handbrakeCLI.exe
*
*/
DirectoryInfo qpath = new DirectoryInfo("Queue");
if (qpath.Exists) {
var mkvFiles = qpath.GetFiles("*.*", SearchOption.AllDirectories).Where(s => s.Extension == ".mkv" || s.Extension == ".mp4");
foreach (var mkvFile in mkvFiles) {
var gParent = mkvFile.Directory.Parent.ToString();
if (gParent.Contains("S")) {
string opath = Path.Combine(mkvFile.Directory.Parent.FullName, "Finished", mkvFile.Name);
string arg = "-i " + mkvFile.FullName + " -o " + opath + " -e x264 " + " --aencoder ac3 " + "-s 1 " + "--subtitle-default 1";
if (!File.Exists(opath))
Process.Start(Environment.CurrentDirectory+ #"\handbrakeCLI.exe", arg);
}
}
}

C# + 7z.exe doesn't seem to work [duplicate]

This question already has answers here:
Unzip a file in c# using 7z.exe
(6 answers)
Closed 8 years ago.
string path = #"C:\Users\<user>\Documents\Visual Studio\Projects\7ZipFile\RequiredDocs\";
ProcessStartInfo zipper = new ProcessStartInfo(#"C:\Program Files\7-Zip\7z.exe");
zipper.Arguments = string.Format("a -t7z {0}.7z {0} *.txt -mx9", path);
zipper.RedirectStandardInput = true;
zipper.UseShellExecute = false;
zipper.CreateNoWindow = true;
zipper.WindowStyle = ProcessWindowStyle.Hidden;
Process process = Process.Start(zipper);
Goal: Zip all *.txt file(s) within "path" and save that zipped file within "path" and these .txt files should not be present in the "path" after zipping
When I run the code, nothing seems to happen (0 error)...
Please help!
Thank you
UPDATE: I am using 7Zip and have installed 7Zip application on Windows where this code will be used w/ .NET 3.5.
The normal way of using 7Zip from a program is to invoke 7za.exe (not the installed 7z program) and include 7za with your application.
This page has a good tutorial on how to use it. Works great every time I have needed to zip/7zip programmatically.
You could also use the ZipArchive class if you want normal zip functionality in a pure .NET way (requires .NET 4.5)
Also, your path should be in quotes in case there is a space. Note that the quotes are escaped with '\'. "" is also a valid escape sequence for a quote in C#:
string.Format("a -t7z \"{0}.7z\" \"{0}\" *.txt -mx9", path);
Here's an example from my application. This example extracts an archive but it shows you how to set up the process. Just change the command to 7z and the arguments. This example assumes you're shipping 7za.exe with your application. Good luck.
public static bool ExtractArchive(string f) {
string tempDir = Environment.ExpandEnvironmentVariables(Configuration.ConfigParam("TEMP_DIR"));
if (zipToolPath == null) return false;
// Let them know what we're doing.
Console.WriteLine("Unpacking '" + System.IO.Path.GetFileName(f) + "' to temp directory.");
LogFile.LogDebug("Unpacking '" + System.IO.Path.GetFileName(f) + "' to temp directory '" + tempDir + "'.",
System.IO.Path.GetFileName(f));
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
if (pid == PlatformID.Win32NT || pid == PlatformID.Win32S || pid == PlatformID.Win32Windows || pid == PlatformID.WinCE) {
p.StartInfo.FileName = "\"" + Path.Combine(zipToolPath, zipToolName) + "\"";
p.StartInfo.Arguments = " e " + "-y -o" + tempDir + " \"" + f + "\"";
} else {
p.StartInfo.FileName = Path.Combine(zipToolPath, zipToolName);
p.StartInfo.Arguments = " e " + "-y -o" + tempDir + " " + f;
}
try {
p.Start();
} catch (Exception e) {
Console.WriteLine("Failed to extract the archive '" + f + "'.");
LogFile.LogError("Exception occurred while attempting to list files in the archive.");
LogFile.LogExceptionAndExit(e);
}
string o = p.StandardOutput.ReadToEnd();
p.WaitForExit();
string[] ls = o.Split('\n');
for (int i = 0; i < ls.Count(); i++) {
string l = ls[i].TrimEnd('\r');
if (l.StartsWith("Error")) {
LogFile.LogError("7za: Error '" + ls[i + 1] + "'.", f);
Console.WriteLine("Failed to extract the archive '" + f + "'.");
return false;
}
}
return true;
}

Merge videos in c# asp.net using ffmpeg

Is it possible to merge the two videos by c# asp.net with the help of ffmpeg. In the ffmpeg documentation they gave us cat command. But it wont works in asp.net. I thought it only for linux.
cat intermediate1.mpg intermediate2.mpg > intermediate_all.mpg
asp.net execute this command but there is no output. Help me.
namespace demo
{
public partial class Default : System.Web.UI.Page
{
protected void Button2_Click(object sender, EventArgs e)
{
string strFile = "cars1.flv";
MergeFiles(strFile);
}
public void MergeFiles(string strFile)
{
string strParam;
string Path_FFMPEG = Server.MapPath("~/ffmpeg/bin/ffmpeg.exe");
//Converting a video into mp4 format
string strOrginal = Server.MapPath("~/Videos/");
strOrginal = strOrginal + strFile;
string strConvert = Server.MapPath("~/Videos/ConvertedFiles/");
string strExtn = Path.GetExtension(strOrginal);
if (strExtn != ".mp4")
{
strConvert = strConvert + strFile.Replace(strExtn, ".mp4");
strParam = "-i " + strOrginal + " " + strConvert;
//strParam = "-i " + strOrginal + " -same_quant " + strConvert;
process(Path_FFMPEG, strParam);
}
//Merging two videos
String video1 = Server.MapPath("~/Videos/Cars1.mp4");
String video2 = Server.MapPath("~/Videos/ConvertedFiles/Cars2.mp4");
String strResult = Server.MapPath("~/Videos/ConvertedFiles/Merge.mp4");
//strParam = "-loop_input -shortest -y -i " + video1 + " -i " + video2 + " -acodec copy -vcodec mjpeg " + strResult;
strParam = " -i " + video1 + " -i " + video2 + " -acodec copy -vcodec mjpeg " + strResult;
process(Path_FFMPEG, strParam);
}
public void process(string Path_FFMPEG, string strParam)
{
try
{
Process ffmpeg = new Process();
ProcessStartInfo ffmpeg_StartInfo = new ProcessStartInfo(Path_FFMPEG, strParam);
ffmpeg_StartInfo.UseShellExecute = false;
ffmpeg_StartInfo.RedirectStandardError = true;
ffmpeg_StartInfo.RedirectStandardOutput = true;
ffmpeg.StartInfo = ffmpeg_StartInfo;
ffmpeg_StartInfo.CreateNoWindow = true;
ffmpeg.EnableRaisingEvents = true;
ffmpeg.Start();
ffmpeg.WaitForExit();
ffmpeg.Close();
ffmpeg.Dispose();
ffmpeg = null;
}
catch (Exception ex)
{
}
}
}
}
Finally i found the answer for my own question.
The following method resolves my problem.
public void MergeFiles(string strFile)
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = Server.MapPath("~/app.bat");
p.Start();
p.WaitForExit();
p.Dispose();
}
app.bat
The app.bat contains the following code.
copy e:\cars1.mpg /b + e:\cars2.mpg /b e:\output.mpg /b
NOTE: This is for windows only. That's why "cat" command doesn't works. Instead of "cat" command we use copy command.
Creating app. Bat file double the file size but it play as single. Still problem not resolved. You should try ffmpeg concat command approach in which you need to create a text file that contain files names and this file should be on same folder where mp4 file are. the below code will help you i was facing the same issue. My task was to merge two mp4 files and I merge successfully when I was doing it from Command prompt. But stuck when I was doiing it through asp. Net. My issue resolved by given correct path and remove ffmpeg from command. For E. G( ffmepg - f concat TO - f concat)
Dim _ffmpeg As String = "D:\Develop\Experiment\mergermp4Vb\mergermp4Vb\bin\ffmpeg.exe"
Dim params = "-f concat -i D:\Develop\Experiment\mergermp4Vb\mergermp4Vb\Videos\mylist2.txt -c copy D:\Develop\Experiment\mergermp4Vb\mergermp4Vb\Videos\0104.mp4"
Dim _FFmpegProcessPropertys As New ProcessStartInfo
_FFmpegProcessPropertys.FileName = _ffmpeg
_FFmpegProcessPropertys.Arguments = params
_FFmpegProcessPropertys.UseShellExecute = False
_FFmpegProcessPropertys.RedirectStandardOutput = True
_FFmpegProcessPropertys.RedirectStandardError = True
_FFmpegProcessPropertys.CreateNoWindow = True
Dim FFmpegProcess = Process.Start(_FFmpegProcessPropertys)

Categories