Get apk infromation using c# - c#

I want to get internal names of apk files and I've tried a lot of ways and I've searched a lot. finally this is what I've got :
Process proc = new Process();
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
proc.Start();
using (StreamWriter sw = proc.StandardInput)
{
foreach (string path in Directories.GetAllFiles(#"E:\apk", "apk"))
{
sw.WriteLine("aapt d badging " + "\"" + path + "\"");
//following line doesn't work because sStandardInput is open
Debug.WriteLine(proc.StandardOutput.ReadToEnd());
}
}
// There will be a really huge amount of text (at least 20 line per sw.Writeline) and
//it impacts performance so following line is not really what I'm looking for
Debug.WriteLine(proc.StandardOutput.ReadToEnd());
GetAllFiles is a function that I've created to fetch all apk file full path. This is not final code.
As I've commented it out first Debug.WriteLine doesn't work and second one is not a good idea. how should I get output from proc?
I have tried running proccess by argument and its awful :)

Related

How do I make sure my external process creates a new file instead of overwriting it?

Below is the code I used to write the file on my destination folder, howerver by some logic if same file I want to create having some different data into it, it gets overwritten on that location.
My requirement is not to overwrite the file but keep the old file as it is and creating new file having similar name but by just appending next copy to it, for example my_file.pdf(1) or something like that
ProcessStartInfo startInfo = new ProcessStartInfo();
string switches = "";
switches += "--header-html " + path + " --footer-html " + footerPath;// + " --header-spacing 10";
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true;
startInfo.FileName = Server.MapPath(ConfigurationManager.AppSettings["wkhtmltopdfsetup"].ToString());
startInfo.Arguments = switches + " " + website + " " + destinationFile;
Process myProcess = Process.Start(startInfo);
string error = myProcess.StandardError.ReadToEnd();
myProcess.WaitForExit();
myProcess.Close();
myProcess.Dispose();
myProcess = null;
You can do something like
//Save file if one does not exist
if (!File.Exists("Your File"))
{
//Save file code here
}
//if file exist then add a datetime stamp to the file name so it does not overwrite the old one
else
{
string newFileName =
Path.Combine(Path.GetDirectoryName("path of the file"),
string.Concat(Path.GetFileNameWithoutExtension("your file"),
DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss"),
Path.GetExtension("your file")));
//Save new file code here
}
You could start by comparing the existing file's size to the new one. If they differ, the files are different. Comparing ends here and you do not need to go further (using more process time). If they do not, they might be the same but we cannot be quite sure. Depending on the way files may differ, you could just compare a chunk of the files content. If the differences are very small or exclusivelly at the end or the begining of the document, compare accordingly. Worse case senario, you will have to compare the whole file.

Print Save as PDF

I have the below code. As per my knowledge it is converting and saving as pdf. Can anyone explain this code?
Process cnp = new Process();
cnp.StartInfo.FileName = "AcroRd64.exe";
cnp.StartInfo.Arguments = "/n /t c:/test.jpg Microsoft Office Document Image Writer";
Updates:
I created a sample console application to trigger print and it is not working
class Program
{
static void Main(string[] args)
{
try
{
Process p = new Process();
p.StartInfo.FileName = #"C:\Program Files (x86)\Adobe\Reader 10.0\Reader\AcroRd32.exe";
p.StartInfo.Verb = "Print";
p.StartInfo.Arguments = "/n /t c:/test.png " + "Microsoft Office Document Image Writer";
p.StartInfo.CreateNoWindow = false;
p.StartInfo.UseShellExecute = true;
p.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadKey();
}
}
Process is used to start and stop processes on your system.
Seems pretty clear that your code attempts to start a process "AcroRd64.exe", which I would guess is the pdf-reader Adobe Acrobat Reader. Argumens are arguments to the process, so basically, this is the equivalent of writing the following in command line:
AcroRd64.exe /n /t c:/test.jpg Microsoft Office Document Image Writer
There's a little more info on this under this other SO question.
Your code might doesn't work because the single argument Microsoft Office Document Image Writer contains whitespace. Try:
cnp.StartInfo.Arguments =
"AcroRd64.exe /n /t c:/test.jpg \"Microsoft Office Document Image Writer\"";

Text content in pdf is not converted using pdf2swf

I am running c# application in service mode. And i am using pdf2swf tool to convert odf to swf format. Images saved in pdf is converting. But if any test adding to pdf is not getting converted in service mode.
But when run as UI mode(Consoleapplication.exe) then everything is getting converted.
string inputFileName = this.Filename;
string outputFileName = inputFileName.Replace("pdf", "swf");
StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0} -o {1}", inputFileName, outputFileName);
string executingDirPath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Replace("file:\\", "");
string dataDirectoryPath = Path.Combine(executingDirPath, "pdf2swf.exe");
ProcessStartInfo psi = new ProcessStartInfo(dataDirectoryPath, sb.ToString());
psi.UseShellExecute = false;
System.Diagnostics.Process pdf2swf = new System.Diagnostics.Process();
pdf2swf.StartInfo = psi;
pdf2swf.Start();
pdf2swf.WaitForExit();
pdf2swf.Close();
pdf2swf.Dispose();
Regards
Sangeetha
Direct using process to start pdf2swf.ext maybe had some privilege problems.I used another way to solve this problem,write a batch file,then running the batch file by process.
Batch file sample:
c:
cd C:\Program Files (x86)\SWFTools\
pdf2swf.exe -f -T 9 -t "%1" -o "%2"
Code in program:
Process p = new Process();
string path = basePath + "/plugin/ConvertToSwf.bat";//batch file path
ProcessStartInfo pi = new ProcessStartInfo(path, filePath + " " + swfPath);//passing the file path and converted file path to batch file
pi.UseShellExecute = false;
pi.RedirectStandardOutput = true;
p.StartInfo = pi;
p.Start();
p.WaitForExit();
I faced a similar problem recently. I solved the issue by adding a separate console application(Consoleapplication.exe) with administrative-rights that runs on my server without shell.
Also, try to upgrade to the newest version of pdf2swf.
FYI. I recently had this problem (thought it was fonts not being embedded but actually was missing all text in converted swf). What fixed it for me was to set:
pi.UseShellExecute = false;
AND set the working directory;
pi.WorkingDirectory = "C:\windows\temp"; // path where read & write is

Reading System.Diagnostics.ProcessStartInfo StandardOutput as bytes instead of chars

I'm trying to automate svnadmin dump using C# ProcessStartInfo.
The way I've done it on the command line is like so,
svnadmin dump c:\Repositories\hackyhacky > c:\backup\hackyhacky.svn_dump
Works a treat and dumps successfully, and I can verify this by restoring it into another repository like so
svnadmin load c:\Repositories\restore_test < c:\backup\hackyhacky.svn_dump
Which restores successfully - yay!
Now... I need to replicate the command line piping into another file using C#, but for some reason
var startInfo = new ProcessStartInfo(Path.Combine(SvnPath, "svnadmin"),"dump c:\Repositories\hackyhacky")
{CreateNoWindow = true, RedirectStandardOutput = true,RedirectStandardError = true,UseShellExecute = false};
process.StartInfo = startInfo;
process.Start();
StreamReader reader = process.StandardOutput;
char[] standardOutputCharBuffer = new char[4096];
byte[] standardOutputByteBuffer;
int readChars = 0;
long totalReadBytes = 0;
// read from the StandardOutput, and write directly into another file
using (StreamWriter writer = new StreamWriter(#"C:\backup\hackyhacky.svn_dump", false)) {
while (!reader.EndOfStream) {
// read some chars from the standard out
readChars = reader.Read(standardOutputCharBuffer, 0, standardOutputCharBuffer.Length);
// convert the chars into bytes
standardOutputByteBuffer = reader.CurrentEncoding.GetBytes(standardOutputCharBuffer);
// write the bytes out into the file
writer.Write(standardOutputCharBuffer.Take(readChars).ToArray());
// increment the total read
totalReadBytes += standardOutputByteBuffer.Length;
}
}
Dumps the same repo into hackyhacky.svn_dump.
But when I run my load command line now
svnadmin load c:\Repositories\restore_test < c:\backup\hackyhacky.svn_dump
I get a checksum error weird-error!
svnadmin load c:\Repositories\restore_test < c:\backup\hackyhacky.svn_dump
< Started new transaction, based on original revision 1
* adding path : Dependencies ... done.
* adding path : Dependencies/BlogML.dll ...svnadmin: Checksum mismatch, fil
e '/Dependencies/BlogML.dll':
expected: d39863a4c14cf053d01f636002842bf9
actual: d19831be151d33650b3312a288aecadd
I'm guessing this is to do with how I'm redirecting and reading the StandardOutput.
Does anyone know the right way to mimic the command line file piping behaviour in C#?
Any help is greatly appreciated.
-CV
UPDATE
I've tried using a BinaryWriter and using the standardOutputByteBuffer to write to the file, but that doesn't work either. I get a different error about incorrect header format or something.
Alright! If you can't beat em, join em....
I found a post where the author pipes to a file directly within the Process StartInfo, and claims it works.
http://weblogs.asp.net/israelio/archive/2004/08/31/223447.aspx
It didn't work for me, as described in another gentleman's post
http://webcache.googleusercontent.com/search?q=cache:http://www.deadbeef.com/index.php/redirecting_the_output_of_a_program_to_a
He writes a batch file first with the piping and then executes it...
amWriter bat = File.CreateText("foo.bat");
bat.WriteLine("#echo off");
bat.WriteLine("foo.exe -arg >" + dumpDir + "\\foo_arg.txt");
bat.Close();
Process task = new Process();
task.StartInfo.UseShellExecute = false;
task.StartInfo.FileName = "foo.bat";
task.StartInfo.Arguments = "";
task.Start();
task.WaitForExit();
In his words:
Truly horrific, but it has the
advantage of working!
To be perfectly frank, I'm a bit annoyed this has taken me as long as it has, so the batch file solution works well so I'm going to stick with it.
The first thing I'd try is writing the character array - not the byte array - to the file.
That should work as long as the output is just simple text. There's other encoding issues, though, if the output is more complex: you're writing the file as UTF-8, whereas the default for command-line output (I believe) is Windows-1252.
I've been trying to do this very thing, and just stumbled on another solution to the problem used by Hector Sosa's svnmanagerlib sourceforge project:
The key to solving this was surrounding the call to WaitForExit() with
file operations. Also needed to make sure to write the output to disk.
Here are the relevant lines:
File.AppendAllText( destinationFile, myOutput.ReadToEnd() );
svnCommand.WaitForExit(); File.AppendAllText(destinationFile,
myOutput.ReadToEnd() );
Notice that I make a call to File.AppendAllText() twice. I have found
that the output stream does not write everything during the first call
to File.AppendAllText() on some occasions.
public static bool ExecuteWritesToDiskSvnCommand(string command, string arguments, string destinationFile, out string errors)
{
bool retval = false;
string errorLines = string.Empty;
Process svnCommand = null;
ProcessStartInfo psi = new ProcessStartInfo(command);
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
try
{
Process.Start(psi);
psi.Arguments = arguments;
svnCommand = Process.Start(psi);
StreamReader myOutput = svnCommand.StandardOutput;
StreamReader myErrors = svnCommand.StandardError;
File.AppendAllText(destinationFile, myOutput.ReadToEnd());
svnCommand.WaitForExit();
File.AppendAllText(destinationFile, myOutput.ReadToEnd());
if (svnCommand.HasExited)
{
errorLines = myErrors.ReadToEnd();
}
// Check for errors
if (errorLines.Trim().Length == 0)
{
retval = true;
}
}
catch (Exception ex)
{
string msg = ex.Message;
errorLines += Environment.NewLine + msg;
}
finally
{
if (svnCommand != null)
{
svnCommand.Close();
}
}
errors = errorLines;
return retval;
}

Executing BatchFile from C# program

I am writing the batch file and executing it through C# program.
Writing Batch file :
I will get the Path, Executable name and arguments from app.config and write them to a batch file.
Executing Batch file :
Once I write the batch file I pass the file name to below function which executes the batch file to launches an application.
Problem :
My program will write a lot of batch files which are executed immediately after each and every file is written. I find that, some times the applications are not started which means that batch files are not executed. I didn't even get any error messages or prompts for this failure of batch file execution.
Expected solution :
Any problem in executing the batch file, I should be able to log it or prompt an error.
Code that executes Batch File :
System.Diagnostics.ProcessStartInfo procinfo = new System.Diagnostics.ProcessStartInfo("cmd.exe");
procinfo.UseShellExecute = false;
procinfo.RedirectStandardError = true;
procinfo.RedirectStandardInput = true;
procinfo.RedirectStandardOutput = true;
System.Diagnostics.Process process = System.Diagnostics.Process.Start(procinfo);
System.IO.StreamReader stream = System.IO.File.OpenText(BatchPath + LatestFileName);
System.IO.StreamReader sroutput = process.StandardOutput;
System.IO.StreamWriter srinput = process.StandardInput;
while (stream.Peek() != -1)
{
srinput.WriteLine(stream.ReadLine());
}
Log.Flow_writeToLogFile("Executed .Bat file : " + LatestFileName);
stream.Close();
process.Close();
srinput.Close();
sroutput.Close();
I'm not sure where your problem lies specifically but I've had no problems with the following code:
using (FileStream file = new FileStream("xyz.cmd", FileMode.Create)) {
using (StreamWriter sw = new StreamWriter(file)) {
sw.Write("#echo ====================\n");
sw.Close();
}
}
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "xyz.cmd";
//p.StartInfo.RedirectStandardOutput = true;
p.Start();
//String s = p.StandardOutput.ReadLine();
//while (s != null) {
// MessageBox.Show(s);
// s = p.StandardOutput.ReadLine();
//}
p.WaitForExit();
Obviously that's been cut down a bit for the purposes of hiding my "secret sauce" but that's code currently being used in production without issues.
I do have one question. Why don't you execute the cmd file directly rather than running cmd.exe?
Probably the first thing I'd do is to print out the BatchPath + LatestFileName value to see if you're creating any weirdly named files which would prevent cmd.exe from running them.

Categories

Resources