run an executable that was downloaded from blob into stream in c# - c#

I've downloaded an executable file from my Cloud blob, and now I want to run the file.
here's my relevant piece of code:
Stream codeContent = new MemoryStream();
blobClientCode.GetBlockBlobReference(codeUri).DownloadToStream(codeContent);
codeContent.Position = 0;
Process p = new Process();
Now I want to run the executable I've downloaded. I guess that I need to use a Process for that, I just don't know how. can anyone please help?
Thanks in advance

Something like this should do. Pass your blob as the first parameter and the local file path as the second:
public static void RunBlob(ICloudBlob blob, string targetFilePath) {
using (var fileStream = File.OpenWrite(targetFilePath)) {
blob.DownloadToStream(fileStream);
}
var process = new Process() {StartInfo = new ProcessStartInfo(targetFilePath)};
process.Start();
process.WaitForExit(); // Optional
}

Related

getting an error that 'the process cannot access the file because it is being used by another process' in my dot net program

I tried 'using' but it says that the method is not Idisposable. I checked for running processes in Task Manager, nothing there. My goal is to upload a file from local directory to the Rich Text editor in my website. Please help me resolve this issue. Thanks in Advance
public void OnPostUploadDocument()
{
var projectRootPath = Path.Combine(_hostingEnvironment.ContentRootPath, "UploadedDocuments");
var filePath = Path.Combine(projectRootPath, UploadedDocument.FileName);
UploadedDocument.CopyTo(new FileStream(filePath, FileMode.Create));
// Retain the path of uploaded document between sessions.
UploadedDocumentPath = filePath;
ShowDocumentContentInTextEditor();
}
private void ShowDocumentContentInTextEditor()
{
WordProcessingLoadOptions loadOptions = new WordProcessingLoadOptions();
Editor editor = new Editor(UploadedDocumentPath, delegate { return loadOptions; }); //passing path and load options (via delegate) to the constructor
EditableDocument document = editor.Edit(new WordProcessingEditOptions()); //opening document for editing with format-specific edit options
DocumentContent = document.GetBodyContent(); //document.GetContent();
Console.WriteLine("HTMLContent: " + DocumentContent);
//string embeddedHtmlContent = document.GetEmbeddedHtml();```
//Console.WriteLine("EmbeddedHTMLContent: " + embeddedHtmlContent);
}
FileStream is disposable, so you can use using on it:
using (var stream = new FileStream(filePath, FileMode.Create)
{
UploadedDocument.CopyTo(stream);
}

How to monitor a logfile that seems to be open all the time (much like notepad++ does)?

I'm trying to build a small program to monitor my pfirewall.log, but I can't seem to open it.
I found quite many (simple) answers, that all kinda say
// use FilesystemWatcher
// open FileStream
// read from last position to end
// output new lines
The problem here is: The file seems to always be opened by another process already. I guess that's the windows process writing to the file, since it's getting written to all the time, as Notepad++ shows me.
Which means, Notepad++ can for some reason do what I can not: Read the file despite it being opened already.
I initialize my monitor in the constructor:
public FirewallLogMonitor(string path)
{
if (!File.Exists(path))
throw new FileNotFoundException("Logfile not found");
this.file = path;
this.lastPosition = 0;
this.monitor = new FileSystemWatcher(Path.GetDirectoryName(path), Path.GetFileName(path));
this.monitor.NotifyFilter = NotifyFilters.Size;
}
And try to read the file on monitor.Changed event:
private void LogFileChanged(object sender, FileSystemEventArgs e)
{
using (FileStream stream = new FileStream(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.Read))
using (StreamReader reader = new StreamReader(stream))
{
stream.Seek(this.lastPosition, SeekOrigin.Begin);
var newLines = reader.ReadToEnd();
this.lastPosition = stream.Length;
var filteredLines = filterLines(newLines);
if (filteredLines.Count > 0)
NewLinesAvailable(this, filteredLines);
}
}
It always throws the IOException on new FileStream(...) to tell me the file is already in use.
Since Notepad++ does it, there has to be a way I can do it too, right?
**Edit: ** A button does this:
public void StartLogging()
{
this.IsRunning = true;
this.monitor.Changed += LogFileChanged;
this.monitor.EnableRaisingEvents = true;
}
**Edit2: ** This is not a duplicate of FileMode and FileAccess and IOException: The process cannot access the file 'filename' because it is being used by another process, since that one assumes I have control over the writing process. Will try the other suggestions, and report back with results.
If i understand your question you can use the notepad++ itself with a plugin to monitor you need to go to:
plugins -> Document Moniter -> Start to monitor
if you dont have this plugin you can download it here:
http://sourceforge.net/projects/npp-plugins/files/DocMonitor/

.dat* filename handling in .Net and Windows

While troubleshooting a performance problem, I came across an issue in Windows 8 which relates to file names containing .dat (e.g. file.dat, file.data.txt).
I found that it takes over 6x as long to create them as any file with any other extension.
The same issue occurs in windows explorer where it takes significantly longer when copying folders containing .dat* files.
I have created some sample code to illustrate the issue.
internal class DatExtnIssue
{
internal static void Run()
{
CreateFiles("txt");
CreateFiles("dat");
CreateFiles("dat2");
CreateFiles("doc");
}
internal static void CreateFiles(string extension)
{
var folder = Path.Combine(#"c:\temp\FileTests", extension);
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
var sw = new Stopwatch();
sw.Start();
for (var n = 0; n < 500; n++)
{
var fileName = Path.Combine(folder, string.Format("File-{0:0000}.{1}", n, extension));
using (var fileStream = File.Create(fileName))
{
// Left empty to show the problem is due to creation alone
// Same issue occurs regardless of writing, closing or flushing
}
}
sw.Stop();
Console.WriteLine(".{0} = {1,6:0.000}secs", extension, sw.ElapsedMilliseconds/1000.0);
}
}
Results from creating 500 files with the following extensions
.txt = 0.847secs
.dat = 5.200secs
.dat2 = 5.493secs
.doc = 0.806secs
I got similar results using:
using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
{ }
and:
File.WriteAllText(fileName, "a");
This caused a problem as I had a batch application which was taking far too long to run. I finally tracked it down to this.
Does anyone have any idea why this would be happening? Is this by design? I hope not, as it could cause problems for high-volume application creating .dat files.
It could be something on my PC but I have checked the windows registry and found no unusual extension settings.
If all else fails, try a kludge:
Write all files out as .txt and then rename *.txt to .dat. Maybe it will be faster :)

Add a file to solution using relative path

I added a text file to my solution in VS2010 and called it test.txt.
In the properties of the file I have set copy to output : always and the build action : content.
How can I open this file in my project now? So that if a user presses a button it will open up the text file.
I have tried several methods, such as File.open("test.txt") and System.Diagnostics.Process.Start(file path)) and nothing has worked.
Can anyone offer up some suggestions?
Since you are using copy to output the file is being placed in the same directory as your program therefore you can use:
System.Diagnostics.Process.Start("test.txt");
or based on this MSDN article:
string path = "test.txt";
using (FileStream fs = File.Open(path, FileMode.Open))
{
byte[] b = new byte[1024];
UTF8Encoding temp = new UTF8Encoding(true);
while (fs.Read(b, 0, b.Length) > 0)
{
textBox1.Text += (temp.GetString(b));
}
}
Hmm... I just tried System.Diagnostics.Process.Start("TextFile1.txt") and it worked. You can try the following:
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo.FileName = "TextFile1.txt";
proc.Start();
If that still doesn't work, go to your \bin\Debug (or \bin\Release if you are running in Release configuration) and make sure that the text file is actually in the same location as your .exe.
What about StreamReader?
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
http://msdn.microsoft.com/en-us/library/db5x7c0d.aspx

Open image in Windows Photo Viewer

How to open .jpg image in Windows Photo Viewer from C# app?
Not inside app like this code,
FileStream stream = new FileStream("test.png", FileMode.Open, FileAccess.Read);
pictureBox1.Image = Image.FromStream(stream);
stream.Close();
I think you can just use:
Process.Start(#"C:\MyPicture.jpg");
And this will use the standard file viewer associated with .jpg files - by default the windows picture viewer.
Start it in a new Process
Process photoViewer = new Process();
photoViewer.StartInfo.FileName = #"The photo viewer file path";
photoViewer.StartInfo.Arguments = #"Your image file path";
photoViewer.Start();
The code fetch photo from ftp and shows the photo in Windows Photo Viewer.
I hope it will usefully for you.
public void ShowPhoto(String uri, String username, String password)
{
WebClient ftpClient = new WebClient();
ftpClient.Credentials = new NetworkCredential(username,password);
byte[] imageByte = ftpClient.DownloadData(uri);
var tempFileName = Path.GetTempFileName();
System.IO.File.WriteAllBytes(tempFileName, imageByte);
string path = Environment.GetFolderPath(
Environment.SpecialFolder.ProgramFiles);
// create our startup process and argument
var psi = new ProcessStartInfo(
"rundll32.exe",
String.Format(
"\"{0}{1}\", ImageView_Fullscreen {2}",
Environment.Is64BitOperatingSystem ?
path.Replace(" (x86)", "") :
path
,
#"\Windows Photo Viewer\PhotoViewer.dll",
tempFileName)
);
psi.UseShellExecute = false;
var viewer = Process.Start(psi);
// cleanup when done...
viewer.EnableRaisingEvents = true;
viewer.Exited += (o, args) =>
{
File.Delete(tempFileName);
};
}
Best Regards...
public void ImageViewer(string path)
{
Process.Start("explorer.exe",path);
}
Path is the file path of the image to be previewed.
I am trying the other answers but they all return the same error about how the location isn't an OS App, so I'm not sure where the issue lies. I did however discover another method to open the file.
string Location_ToOpen = #"The full path to the file including the file name";
if (!File.Exists(Location_ToOpen))
{
return;
}
string argument = "/open, \"" + Location_ToOpen + "\"";
System.Diagnostics.Process.Start("explorer.exe", argument);
It starts out by testing if the file exists or not. If it doesn't exist it would have caused an error.
After that it simulates a "open" request on a file explorer without opening a file explorer, then the system opens the file with the default app.
I am currently using this method in my project so I hope it works for you too.

Categories