.InvalidOperationException in Process.start - c#-4.0

I have the following code
foreach (Items it in sortedList)
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = true;
startInfo.FileName = it.filePath;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
try
{
Process p = new Process();
p.StartInfo = startInfo;
p.Start();
p.WaitForExit();
}
catch(Exception ew)
{
// Log error.
}
}
Every time I open a mp4 file I get an
InvalidOperationException
and it says that there is no program linked to this format, but at the same time the windows media player starts up and shows the file.
Can someone explain to me why this code is throwing the InvalidOperationException and also how I can fix the issue?
Thanks.

Related

FileInputStream issue - App has stopped working

I am having trouble with FileInputStream in Android Studio. My application has stopped working when I use it to read file .txt in the internal memory (I have writen data to this file successfully). I have try many solutions but they didn't work. Can anyone give the solution for this problem? Here is my code. Thanks very much. (I have added users-permission "WRITE_EXTERNAL_STORAGE" and "READ_EXTERNAL_STORAGE").
String fileName = "infoProfile.txt";
private int readData() {
try {
String path = MainActivity.this.getFilesDir().getAbsolutePath() + "/" + fileName;
FileInputStream in = openFileInput(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
ArrayList<String> str = new ArrayList<>();
String data = "";
while ((data = reader.readLine()) != null) {
str.add(data);
}
in.close();
if (str.isEmpty())
return 0;
etName.setText(str.get(0));
etEmail.setText(str.get(1));
etPhone.setText(str.get(2));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}

How to allow a file to be read by multiple users/process at a time on web server

I am using below code in asp.net webapi for audio streaming to allow android application to call api and play songs.
public class AudioController : ApiController
{
ITrackRepository _TrackRepo = new TrackRepository();
public AudioController()
{
}
public HttpResponseMessage Get(int id)
{
var trackd = _TrackRepo.GetPlayfilepath(id);
string filename = System.Web.HttpContext.Current.Server.MapPath(trackd.Select(x => x.FilePath).FirstOrDefault());
var audio = new AudioStream(filename);
string fileExtension = System.IO.Path.GetExtension(filename);
var response = Request.CreateResponse();
response.Content = new PushStreamContent(audio.WriteToStream, new MediaTypeHeaderValue("audio/" + fileExtension));
return response;
}
}
public class AudioStream
{
private readonly string _filename;
public AudioStream(string filename)
{
_filename = filename;
}
public async void WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
{
try
{
var buffer = new byte[65536];
using (var video = File.Open(_filename, FileMode.Open, FileAccess.Read))
{
var length = (int)video.Length;
var bytesRead = 1;
while (length > 0 && bytesRead > 0)
{
bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
await outputStream.WriteAsync(buffer, 0, bytesRead);
length -= bytesRead;
}
}
}
catch (HttpException ex)
{
return;
}
finally
{
outputStream.Close();
}
}
}
I am able to play song, i tested it with vlc (stream) and its working fine, Issue is when i try to play same song in parallel in another player its giving me below error
The process cannot access the file because it is being used by another
process.
I completely understand error, but i am not able to find any satisfactory solution.
one solution is to create a copy of song before play/stream and delete it on completion but i don't think that is a good solution.
please suggest.
I'm not at a computer with visual studio on it at the moment, but look at this overload for File.Open
Try changing this line:
using (var video = File.Open(_filename, FileMode.Open, FileAccess.Read))
to
using (var video = File.Open(_filename, FileMode.Open, FileAccess.Read, FileShare.Read))
See if that helps.

C# Trying to retrieve %logonserver% from remote machine

I've seen a couple examples here and there, here's what I'm trying to achieve. I know the below does not work, but essentially I'm trying to pull the %logonserver% from a remote machine. For some reason, the wmi query does not return any data.
try
{
System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo("\\\\"+txtboxMachineName.Text+"\\c$\\Windows\\System32\\cmd.exe", "/c echo %logonserver%");
startinfo.RedirectStandardOutput = true;
startinfo.UseShellExecute = false;
startinfo.CreateNoWindow = true;
System.Diagnostics.Process proc = new Process();
proc.StartInfo = startinfo;
proc.Start();
lblLogonServer.Text = proc.StandardOutput.ReadToEnd();
}
catch
{
lblLogonServer.Text = "Error has been encountered obtaining Logon Server";
}

Windows Azure Project - windows service Error 1053 The service did not respond to the start or control request in timely fashion

I have created one Windows Azure project in .net framework 4, visual studio 2010.
Windows Azure SDK version is 1.8.
I have created one windows service to accomplish the running of daily Scheduled tasks.
Below is the code for that -
public partial class EdService1 : ServiceBase
{
public EdService1()
{
InitializeComponent();
}
#region On Start
protected override void OnStart(string[] args)
{
//System.Diagnostics.Debugger.Break();
//Thread thread = new Thread(new ThreadStart(ServiceStart));
//thread.IsBackground = true;
//thread.Name = "ThreadServiceStart";
//thread.Start();
#region Email Utility timer set and call
try
{
TraceService("start service");
timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(this.ServiceTimer_Tick);
this.timer.Interval = 300000;//300000; //60000 millisecond = 1 minute
timer.AutoReset = true;
timer.Enabled = true;
timer.Start();
ServiceTimer_Tick(null, null);
#endregion
#region Daily Utility timer set and call
Dailytimer = new System.Timers.Timer();
Dailytimer.Elapsed += new ElapsedEventHandler(this.DailyTimer_Tick);
this.Dailytimer.Interval = 7200000; //60000 millisecond = 1 minute
Dailytimer.AutoReset = true;
Dailytimer.Enabled = true;
Dailytimer.Start();
DailyTimer_Tick(null, null);
#endregion
}
catch (Exception ex)
{
throw new Exception(ex.Message.ToString());
}
}
#endregion
public void ServiceStart()
{
#region Email Utility timer set and call
TraceService("start service");
timer = new System.Timers.Timer();
timer.Elapsed += new ElapsedEventHandler(this.ServiceTimer_Tick);
this.timer.Interval = 300000;//300000; //60000 millisecond = 1 minute
timer.AutoReset = true;
timer.Enabled = true;
timer.Start();
ServiceTimer_Tick(null, null);
#endregion
#region Daily Utility timer set and call
Dailytimer = new System.Timers.Timer();
Dailytimer.Elapsed += new ElapsedEventHandler(this.DailyTimer_Tick);
this.Dailytimer.Interval = 7200000; //60000 millisecond = 1 minute
Dailytimer.AutoReset = true;
Dailytimer.Enabled = true;
Dailytimer.Start();
DailyTimer_Tick(null, null);
#endregion
}
#region Sending Email Utility
private void ServiceTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
{
strErrorMessage = string.Empty;
string strEmailError = "";
try
{
// calling functions here
}
catch (Exception ex)
{
strErrorMessage = ex.ToString();
}
if (strErrorMessage != "")
{
string strIPAddress = GetLocalIPAddress();
SendEmail("Error in Sending Email Utility " + strIPAddress, strErrorMessage.Replace("#", "\n </br>"), EmailFrom, EmailTo, ref strEmailError, EmailCC);
}
}
private void TraceService(string content)
{
//set up a filestream
FileStream fs = new FileStream(#"c:\ScheduledService.txt", FileMode.OpenOrCreate, FileAccess.Write);
//set up a streamwriter for adding text
StreamWriter sw = new StreamWriter(fs);
//find the end of the underlying filestream
sw.BaseStream.Seek(0, SeekOrigin.End);
//add the text
sw.WriteLine(content);
//add the text to the underlying filestream
sw.Flush();
//close the writer
sw.Close();
}
protected override void OnStop()
{
timer.AutoReset = false;
timer.Enabled = false;
TraceService("stopping service");
}
I tried to start this service with local and administrator account. But getting this mentioned error message.
Even I am not sure how to test this methods onStart() for this service. I tried diagnostics code but it doesn't stop there.
Can anyone please help me on this?
Thanks.

ProcessStartInfo Browser Output

I have tried everything I can think of and every code sample imaginable but I cannot get any type of output using Process.Start when opening a browser. I have tried just looking at error output and eliciting 404 errors and Standard Output using actual URLs - nothing works. Here is the simplest example - although it fails as well even though the browser launches every time...
//Default Browser
RegistryKey key = null;
string defaultPath = "";
try
{
key = Registry.ClassesRoot.OpenSubKey("HTTP\\shell\\open\\command", false);
defaultPath = key.GetValue("").ToString().ToLower().Replace("\"", "");
if (!defaultPath.EndsWith(".exe"))
defaultPath = defaultPath.Substring(0, defaultPath.LastIndexOf(".exe") + 4);
}
catch { }
finally
{
if (key != null)
key.Close();
}
None Working Code:
ProcessStartInfo browserInfo = new ProcessStartInfo();
browserInfo.CreateNoWindow = true;
browserInfo.WindowStyle = ProcessWindowStyle.Hidden;
browserInfo.FileName = defaultPath;
browserInfo.Arguments = "http://www.google.com";
browserInfo.UseShellExecute = false;
browserInfo.RedirectStandardError = true;
browserInfo.RedirectStandardOutput = true;
string error = "";
string output = "";
String strProcessResults;
try
{
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = defaultPath;
p.StartInfo.Arguments = "http://www.google.com/NoneYa.html";
p.Start();
// Read the output stream first and then wait.
strProcessResults = p.StandardError.ReadToEnd();
p.WaitForExit();
}
catch (System.ComponentModel.Win32Exception BrowserX)
{
//We ignore the error if a browser does not exist!
if (BrowserX.ErrorCode != -2147467259)
throw BrowserX;
}
OR
try
{
// Start the child process.
Process p = new Process();
// Redirect the output stream of the child process.
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.FileName = defaultPath;
p.StartInfo.Arguments = "http://www.google.com";
p.Start();
// Read the output stream first and then wait.
strProcessResults = p.StandardOutput.ReadToEnd();
p.WaitForExit();
}
catch (System.ComponentModel.Win32Exception BrowserX)
{
//We ignore the error if a browser does not exist!
if (BrowserX.ErrorCode != -2147467259)
throw BrowserX;
}
I've never actually checked, but I'd be surprised if your browser printed anything to stdout. It's a Windowed application.

Resources