Cannot Convert From Double To String c# [closed] - c#

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have tried this, but it is giving me an error of "cannot convert from double to string", I wanted to change a variable ProgressBarMegabyte to the equation below.
ProgressBarMegabyte = (Int32.Parse(ProgressBarMegabyte) + Double.Parse(Convert.ToString(ProgressedMegabytes)));
My Whole Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
namespace SoftwareStoreClientDownloader
{
public partial class OfflineInstaller : Form
{
public OfflineInstaller()
{
InitializeComponent();
FormClosing += OfflineInstaller_FormClosing;
}
private void OfflineInstaller_FormClosing(object sender, FormClosingEventArgs e)
{
File.WriteAllText("C:\\Closed.txt", "true");
}
private void OfflineInstaller_Load(object sender, EventArgs e)
{
if (!Directory.Exists("C:\\Program Files\\SoftwareStoreOffline"))
{
Directory.CreateDirectory("C:\\Program Files\\SoftwareStoreOffline");
}
}
private void BrowseButton_Click(object sender, EventArgs e)
{
SaveFileDialog s = new SaveFileDialog();
s.DefaultExt = "iso";
s.AddExtension = false;
s.CheckPathExists = true;
s.ShowDialog();
try
{
BrowseFileTextBox.Text = s.FileName;
}
catch (Exception dew)
{
}
}
private async void button1_Click(object sender, EventArgs e)
{
var i = 2;
button1.Enabled = false;
button1.Text = "Initializing";
await Initialize();
button1.Text = "Downloading";
TotalProgressBar.Maximum = Int32.Parse(Parts);
if (Int32.Parse(Parts) > 99)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part001.exe",
MainDirectory + "\\" + "Setup-Files.part001.exe");
}
else
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part01.exe",
MainDirectory + "\\" + "Setup-Files.part01.exe");
}
var TotalProgressBytes = ((Int32.Parse(TotalBytes) / 1024d / 1024d) * Int32.Parse(Parts));
var TotalMegabytes = TotalProgressBytes;
var ProgressedMegabytes = (Int32.Parse(TotalBytes) / 1024d / 1024d);
var ProgressBarMegabyte = string.Empty;
ProgressBarMegabyte = ProgressedMegabytes.ToString();
while (i < Int32.Parse(Parts) + 1)
{
if (Int32.Parse(Parts) < 100)
{
if (i < 10)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part0" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part0" + i + ".rar");
}
else
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part" + i + ".rar");
}
}
else if (Int32.Parse(Parts) > 99)
{
if (i < 10 && i < 100)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part00" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part00" + i + ".rar");
}
else if(i > 10 && i < 100)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part0" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part0" + i + ".rar");
}
else if (i > 99)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part" + i + ".rar");
}
}
else if (Int32.Parse(Parts) < 10)
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline" + Database +
"/master/SoftwareStore" + Version + "Setup-Files.part" + i + ".rar",
MainDirectory + "\\" + "Setup-Files.part" + i + ".rar");
}
DownloadProgressLabel.Text = "Status: (" + i + "/" + Parts + ")";
if (i < TotalProgressBar.Maximum)
{
TotalProgressBar.Value = i;
}
if (first == false)
{
TotalProgressLabel.Text = "(" + ProgressBarMegabyte + " MB / " + TotalMegabytes + " MB)";
first = true;
}
else
{
TotalProgressLabel.Text = "(" + ProgressBarMegabyte + " MB / " + TotalMegabytes + " MB)";
}
int Equation = Convert.ToInt32(Int32.Parse(ProgressBarMegabyte) +
Double.Parse(Convert.ToString(ProgressedMegabytes)));
ProgressBarMegabyte = Equation.ToString();
i++;
}
if (Int32.Parse(Parts) > 99)
{
await Task.Factory.StartNew(() =>
{
Process.Start(#"C:\Program Files\SoftwareStoreOffline\Setup-Files.part001.exe").WaitForExit();
});
}
else if (Int32.Parse(Parts) < 100)
{
await Task.Factory.StartNew(() =>
{
Process.Start(#"C:\Program Files\SoftwareStoreOffline\Setup-Files.part01.exe");
});
}
else if(Int32.Parse(Parts) < 10)
{
await Task.Factory.StartNew(() =>
{
Process.Start(#"C:\Program Files\SoftwareStoreOffline\Setup-Files.part1.exe");
});
}
}
private bool first = false;
private string MainDirectory = "C:\\Program Files\\SoftwareStoreOffline";
private string TotalBytes = string.Empty;
private async Task Download(string link, string Filename)
{
using (var client = new WebClient())
{
client.DownloadProgressChanged += Client_DownloadProgressChanged;
client.DownloadFileCompleted += Client_DownloadFileCompleted;
client.DownloadFileAsync(new Uri(link), Filename);
while (client.IsBusy)
{
await Task.Delay(10);
}
}
}
private void Client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (e.Cancelled)
{
}
else if (e.Error != null)
{
}
else
{
}
}
private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
TotalBytes = e.TotalBytesToReceive.ToString();
DownloadProgressBar.Value = e.ProgressPercentage;
}
private string Parts = string.Empty;
private string Database = string.Empty;
private string Version = string.Empty;
private async Task Initialize()
{
try
{
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineDatabaseNumber.txt",
MainDirectory + "\\OfflineDatabaseNumber.txt");
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineParts.txt",
MainDirectory + "\\OfflineParts.txt");
await Download(
"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineVersion.txt",
MainDirectory + "\\OfflineVersion.txt");
Parts = File.ReadLines(MainDirectory + "\\OfflineParts.txt").First();
Database = File.ReadLines(MainDirectory + "\\OfflineDatabaseNumber.txt").First();
Version = File.ReadLines(MainDirectory + "\\OfflineVersion.txt").First();
}
catch (Exception dew)
{
Console.WriteLine(dew);
throw;
}
}
}
}
I'm trying to use that equation, because I wanted to solve the progress bar, which I eventually figured out. I used the int

Instead of using the Convert.ToString()
you can simply do: ProgressedMegabytes.ToString()

You problem is with different types:
ProgressBarMegabyte is a string
ProgressedMegabytes is double as you said.
Then your assignent is:
sting = int + double
Hence you error. To fix it - simply convert the result to string:
double ProgressedMegabytes = 1.5;
string ProgressBarMegabyte = "83345603 .....................";
ProgressBarMegabyte = (Int32.Parse(ProgressBarMegabyte.TrimEnd('.')) + ProgressedMegabytes).ToString();
Console.WriteLine(ProgressBarMegabyte); // 83345604.5
And be careful with the value of ProgressBarMegabyte - you are working with an assumption that it is a number!

This is not an answer to your question - I just wanted to post a refactored version of your code that might help you to move forward.
private async void button1_Click(object sender, EventArgs e)
{
var i = 2;
await Initialize();
var name = Parts > 99 ? "part001" : "part01";
await Download($"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline{Database}/master/SoftwareStore{Version}Setup-Files.{name}.exe", $"{MainDirectory}\\Setup-Files.{name}.exe");
var format = new string('0', Parts.ToString().Length)
while (i < Parts + 1)
{
await Download($"https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreOffline{Database}/master/SoftwareStore{Version}Setup-Files.part{i.ToString(format)}.rar", $"{MainDirectory}\\Setup-Files.{i.ToString(format)}.rar");
i++;
}
await Task.Factory.StartNew(() =>
{
Process.Start($#"C:\Program Files\SoftwareStoreOffline\Setup-Files.part{1.ToString(format)}.exe").WaitForExit();
});
}
private string MainDirectory = "C:\\Program Files\\SoftwareStoreOffline";
private async Task Download(string link, string Filename)
{
using (var client = new WebClient())
{
await client.DownloadFileTaskAsync(link, Filename);
}
}
private int Parts;
private string Database = string.Empty;
private string Version = string.Empty;
private async Task Initialize()
{
try
{
await Download("https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineDatabaseNumber.txt", MainDirectory + "\\OfflineDatabaseNumber.txt");
await Download("https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineParts.txt", MainDirectory + "\\OfflineParts.txt");
await Download("https://raw.githubusercontent.com/CNTowerGUN/SoftwareStoreClientDownloader/master/OfflineVersion.txt", MainDirectory + "\\OfflineVersion.txt");
Parts = int.Parse(File.ReadLines(MainDirectory + "\\OfflineParts.txt").First());
Database = File.ReadLines(MainDirectory + "\\OfflineDatabaseNumber.txt").First();
Version = File.ReadLines(MainDirectory + "\\OfflineVersion.txt").First();
}
catch (Exception dew)
{
Console.WriteLine(dew);
throw;
}
}

I solved the problem myself using cheap methods:
int Equation = Convert.ToInt32(Int32.Parse(ProgressBarMegabyte)
+ Double.Parse(Convert.ToString(ProgressedMegabytes)));
ProgressBarMegabyte = Equation.ToString();

Related

c# not downloading file in stand alone mode but works in debug mode fine

good evening all,
i been working on a little downloader for my program only downloads the python installer small little things will be adding more over time,
however i have a issue when i run it in debug it works downloads fine
when i do it in the debug folder and run the exe without visual studio it load the update box but creates a file with 0 bytes and says when trying to load,
this is not compatible with your os
code i have.
private string GetFileName(string url)
{
string[] parts = url.Split('/');
string fileName = "";
if (parts.Length > 0)
fileName = parts[parts.Length - 1];
else
fileName = url;
return fileName;
}
private String getFileName(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
string fileName = "";
try
{
HttpWebResponse res = (HttpWebResponse)request.GetResponse();
using (Stream rstream = res.GetResponseStream())
{
fileName = res.Headers["Content-Disposition"] != null ?
res.Headers["Content-Disposition"].Replace("attachment; filename=", "").Replace("\"", "") :
res.Headers["Location"] != null ? Path.GetFileName(res.Headers["Location"]) :
Path.GetFileName(url).Contains('?') || Path.GetFileName(url).Contains('=') ?
Path.GetFileName(res.ResponseUri.ToString()) : GetFileName(url);
}
res.Close();
}
catch { }
return fileName;
}
public async Task downloadupdate()
{
if(os == "x86")
{
filename = getFileName("https://www.python.org/ftp/python/3.11.0/python-3.11.0-amd64.exe");
string url = "https://www.python.org/ftp/python/3.11.0/python-3.11.0-amd64.exe";
lblfilename.Text = "File Name: " + getFileName(url);
using (WebClient wc = new WebClient())
{
wc.DownloadFileCompleted += wc_completed;
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
XtraMessageBox.Show(filename);
filename = "python.exe";
wc.DownloadFileAsync(new Uri(url), "C://Temp" + "//" + filename);
}
}
else
{
filename = getFileName("https://www.python.org/ftp/python/3.11.0/python-3.11.0.exe");
string url = "https://www.python.org/ftp/python/3.11.0/python-3.11.0.exe";
lblfilename.Text = "File Name: " + getFileName(url);
using (WebClient wc = new WebClient())
{
wc.DownloadFileCompleted += wc_completed;
wc.DownloadProgressChanged += wc_DownloadProgressChanged;
wc.DownloadFileAsync(new Uri(url), "C://Temp" + "//" + filename);
}
}
}
private void wc_completed(object sender, AsyncCompletedEventArgs e)
{
_MessageResult.Instance.Append("Download Completed!");
//unzipupdate(Tiaga_Res.unzipupdate = "fixes19.zip");
//DirectoryCopy(Tiaga_Res.startpath + "\\fixes19\\", Tiaga_Res._bo3_root, true);
//XtraMessageBox.Show("Applied Fix Aug And Reflex Sight Fix");
// richTextBox1.Text = _MessageResult.Instance.Merge();
Process.Start("C://Temp" + "//" + filename);
this.Close();
}
void wc_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBarControl1.Properties.Step = 1;
progressBarControl1.Properties.PercentView = true;
//progressBarControl1.Properties.Maximum = e.ProgressPercentage;
progressBarControl1.PerformStep();
UpdateProgressBar(e.ProgressPercentage);
txtpercent.Text = e.ProgressPercentage + "%";
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
lbldownloaded.Text = "Downloaded: " + bytesIn + "/" + totalBytes;
}
private void UpdateProgressBar(int value)
{
progressBarControl1.EditValue = value;
}
screen shot of in debug.
any help would be much appreciated i cant see it would be a libz issue i used that since day one to compile dlls into my project never had this issue before

Converting WebClient code to HttpClient code

I need help converting this WebClient to HttpClient code if it's possible, I will be really happy if it is.
I've been looking for something/someone that will convert it to me and I sadly didn't find anything.
Thanks!
private void bunifuFlatButton9_Click(object sender, EventArgs e)
{
{
using (WebClient webClient = new WebClient())
{
webClient.Encoding = Encoding.UTF8;
webClient.DownloadDataCompleted += new DownloadDataCompletedEventHandler(this.Complete);
webClient.DownloadDataAsync(new Uri("https://www.bing.com/search?q=site:pastebin.com+" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://www.bing.com/search?q=site:pastebin.com+" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://duckduckgo.com/?q=site%3Apastebin.com+" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://duckduckgo.com/?q=site%3Apastebin.com+" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://duckduckgo.com/?q=site%3Apastebin.com+" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
webClient.DownloadDataAsync(new Uri("https://yandex.ru/search/?text=" + this.textBox1.Text));
}
}
}
private void Complete(object sender, DownloadDataCompletedEventArgs e)
{
MatchCollection matchCollection = Regex.Matches(new UTF8Encoding().GetString(e.Result), "(https:\\/\\/pastebin.com\\/\\w+)");
int num = checked(matchCollection.Count - 1);
int i = 0;
while (i <= num)
{
using (WebClient webClient = new WebClient())
{
webClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(this.Complete2);
webClient.DownloadStringAsync(new Uri(matchCollection[i].Value));
}
checked { ++i; }
}
}
You should do something like this:
HttpClient client = new HttpClient();
List<string> urls = new List<string>();
urls.Add("https://www.bing.com/search?q=site:pastebin.com+" + this.textBox1.Text);
urls.Add("https://www.bing.com/search?q=site:pastebin.com+" + this.textBox1.Text);
//and so on...
foreach(var url in urls)
{
client.GetAsync(url)
.ContinueWith(async (T) => {
string result = await T.Result.ReadAsStringAsync();
OnComplete(result);
});
}
Then:
public void OnComplete(string result)
{
//todo: convert your result to utf-8 and so on...
}
You can do some exception handling inside ContinueWith block to prevent errors.

C# WUApiLib: Failing to Install Updates with 0x80240024 Even Though Updates are Found

I have followed instructions found on this site, which was found when I researched Stack Overflow and found this question. However, I can't seem to figure out why my code is hitting the catch block. I have a break at the IInstallationResult line, which the code hits but then goes to the catch, stating 0x80240024 (There are no updates), even though there are certainly updates available and I list them in the text box.
What am I missing here?
using System;
using System.Windows.Forms;
using WUApiLib;
namespace TEST.DetectWindowsUpdate
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void GetUpdates(bool downloadUpdates, bool installUpdates)
{
UpdateSession uSession = new UpdateSession();
IUpdateSearcher uSearcher = uSession.CreateUpdateSearcher();
UpdateCollection updatesToInstall = new UpdateCollection();
UpdateDownloader downloader = uSession.CreateUpdateDownloader();
IUpdateInstaller installer = uSession.CreateUpdateInstaller();
uSearcher.Online = true;
try
{
ISearchResult sResult = uSearcher.Search("IsInstalled=0 And Type='Software'");
lblUpdateCount.Text = sResult.Updates.Count.ToString();
foreach (IUpdate update in sResult.Updates)
{
txtUpdatesList.AppendText("Title: " + update.Title + Environment.NewLine);
txtUpdatesList.AppendText("IsInstalled: " + update.IsInstalled.ToString() + Environment.NewLine);
txtUpdatesList.AppendText("Downloaded: " + update.IsDownloaded.ToString() + Environment.NewLine);
txtUpdatesList.AppendText("IsMandatory: " + update.IsMandatory.ToString() + Environment.NewLine);
txtUpdatesList.AppendText(Environment.NewLine);
if (downloadUpdates)
{
if (update.IsDownloaded == false)
{
do
{
downloader.Updates.Add(update);
downloader.Download();
}
while (update.IsDownloaded == false);
if (update.IsDownloaded == true)
{
updatesToInstall.Add(update);
}
}
else
{
updatesToInstall.Add(update);
}
}
if (installUpdates)
{
installer.Updates = updatesToInstall;
IInstallationResult installationRes = installer.Install();
for (int i = 0; i < updatesToInstall.Count; i++)
{
txtUpdatesList.AppendText("Installing " + updatesToInstall[i].Title + "...");
if (installationRes.GetUpdateResult(i).HResult == 0)
{
txtUpdatesList.AppendText("INSTALL SUCCESS FOR " + updatesToInstall[i].Title);
}
else
{
txtUpdatesList.AppendText("INSTALL FAIL FOR " + updatesToInstall[i].Title);
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message + ": " + ex.HelpLink);
}
}
private void btnGetUpdates_Click(object sender, EventArgs e)
{
base.OnLoad(e);
txtUpdatesList.Clear();
GetUpdates(false, false);
}
private void btnInstallUpdates_Click(object sender, EventArgs e)
{
base.OnLoad(e);
txtUpdatesList.Clear();
GetUpdates(true, true );
}
}
}
Turns out it was an issue with privileges. I ran as administrator and it functioned appropriately.

Form without movement when filling in DataGridView

I use a DataGridView as a console for an application, I need to fill it out every second, I use the following code for this:
public class dgView
{
public static DataGridView DataConsole;
public static void addLinha(int tipo_acao, string acao, string extra, int tipo_extra)
{
// INSERE LINHA NO CONSOLE
try
{
if (DataConsole == null) return;
var idLinha = DataConsole.Rows.Add();
using (var linha = DataConsole.Rows[idLinha])
{
//await Task.Delay(300);
if (tipo_acao == 0)
{
linha.DefaultCellStyle.ForeColor = Color.Teal;
linha.Cells[3].Style.ForeColor = Color.Gray;
}
else if (tipo_acao == 1)
{
linha.DefaultCellStyle.ForeColor = Color.Yellow;
linha.Cells[3].Style.ForeColor = Color.Orange;
}
else
{
linha.DefaultCellStyle.ForeColor = Color.Red;
linha.Cells[3].Style.ForeColor = Color.Magenta;
}
linha.Cells["dg_data"].Value = DateTime.Now;
linha.Cells["dg_mapa"].Value = "" + Config.Mapa + "";
linha.Cells["dg_acao"].Value = "" + Config.rm.GetString("" + acao + "") + "";
if (tipo_extra == 0)
{
linha.Cells["dg_extra"].Value = "" + extra + "";
}
else
{
linha.Cells["dg_extra"].Value = "" + Config.rm.GetString(extra) + "";
}
DataConsole.CurrentCell = DataConsole.Rows[idLinha].Cells[0];
//DataConsole.Refresh();
}
}
catch (Exception ex)
{
throw;
}
}
}
However, the form freezes and I can't move it to any part of the screen, would there be any way to solve this? Remembering that the DataGridView is not, and cannot be populated through the DataSource property, but by a constant verification in the system.
Example:
public static void Abrir(string metodoChamador)
{
try
{
Abrir:
dgView.addLinha(2, "config_Abrir", "config_Validando", 1);
Thread.Sleep(5000);
Atalho:
string AtalhoExiste = "" + Directory.GetCurrentDirectory() + "\\" + Config.Atalho + ".lnk";
if (!File.Exists(AtalhoExiste))
{
dgView.addLinha(2, "config_FaltaIcone", "", 0);
Thread.Sleep(5000);
goto Atalho;
}
else
{
ProcessStartInfo info = new ProcessStartInfo(#"" + Directory.GetCurrentDirectory() + "\\" + Config.Atalho + ".lnk");
Process whatever = Process.Start(info);
whatever.Dispose();
Thread.Sleep(5000);
IntPtr WinHandle = Win32.FindWindow(null, Config.Atalho);
if (WinHandle == (IntPtr)0)
{
goto Abrir;
}
}
}
catch (Exception ex)
{
throw;
}
}
It's hard to tell if you have other potential problems in the code. Basically anywhere you have Thread.Sleep(), your GUI is going to freeze.
Here's a possible refactoring of your Abrir() method, using async\await and Task.Delay() as suggested by JQSOFT:
public async static void Abrir(string metodoChamador)
{
try
{
IntPtr WinHandle = IntPtr.Zero;
do
{
dgView.addLinha(2, "config_Abrir", "config_Validando", 1);
await Task.Delay(5000);
string AtalhoExiste = "" + Directory.GetCurrentDirectory() + "\\" + Config.Atalho + ".lnk";
while (!File.Exists(AtalhoExiste))
{
dgView.addLinha(2, "config_FaltaIcone", "", 0);
await Task.Delay(5000);
}
ProcessStartInfo info = new ProcessStartInfo(#"" + Directory.GetCurrentDirectory() + "\\" + Config.Atalho + ".lnk");
Process whatever = Process.Start(info);
whatever.Dispose();
await Task.Delay(5000);
WinHandle = Win32.FindWindow(null, Config.Atalho);
}
while (WinHandle.Equals(IntPtr.Zero));
}
catch (Exception ex)
{
throw;
}
}
If you have Thread.Sleep() in other locations, they would need to be refactored.
If you have any other infinite loops using goto, those may need to be refactored as well.

Why does program lag and freeze while starting process?

I have a code that is supposed to start a process in order to render animation. It works great and starts the process and all, but while the process is running, my program says not responding, and freezes refusing to update progress at all.
Here is the code that should be causing the issue:
void Render()
{
while (currentFrame <= lastFrame)
{
bool rendering = IsRendering("cmd");
if (rendering == false)
{
StreamWriter renderBatch = new StreamWriter(batchFile);
renderBatch.Write('"' + renderPathField.Text + '"' + " -rd " + '"' + imagePath.Text + '"' + " -s " + currentFrame + " -e " + currentFrame + " " + '"' + sceneFile.Text + '"');
renderBatch.Close();
var renderProcess = new Process();
renderProcess.StartInfo = new ProcessStartInfo(batchFile);
//renderProcess.StartInfo.Arguments = '"' + renderPathField.Text + '"' + " -rd " + '"' + imagePath.Text + '"' + " -s " + currentFrame + " -e " + currentFrame + " " + '"' + sceneFile.Text + '"';
renderProcess.StartInfo.UseShellExecute = false;
//renderProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
renderProcess.Start();
if (renderProcess.HasExited == true && currentFrame < lastFrame)
{
ProgressBar1.Value = (currentFrame - 1) / lastFrame;
currentFrame++; //goes onto the next frame once it is done rendering this frame
}
}
}
}
Here is the full code that it is in:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
//using System.Net;
using System.Diagnostics;
using System.IO;
namespace Maya_Network_Render
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// Globals ///////////////////////////////////////
string prefFile = "C:\\Program Files\\Maya Render Buddy Preferences\\options.txt";
string batchFile = "C:\\Program Files\\Maya Render Buddy Preferences\\render.bat";
int firstFrame;
int lastFrame;
int currentFrame;
// Globals //////////////////////////////////////
private void Form1_Load(object sender, EventArgs e)
{
if (Directory.Exists("C:\\Program Files\\Maya Render Buddy Preferences"))
{
if (File.Exists(prefFile))
{
StreamReader preferences = new StreamReader(prefFile);
string renderFilePath = preferences.ReadLine();
renderPathField.Text = renderFilePath;
preferences.Close();
}
else
{
File.Create(prefFile);
}
}
else
{
Directory.CreateDirectory("C:\\Program Files\\Maya Render Buddy Preferences");
File.Create(prefFile);
}
}
private void sceneBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog scenefinder = new OpenFileDialog();
scenefinder.Title = "Browse to your Maya scene file";
scenefinder.RestoreDirectory = true;
if (scenefinder.ShowDialog() == DialogResult.OK)
{
sceneFile.Text = scenefinder.FileName;
}
}
private void imageBrowse_Click(object sender, EventArgs e)
{
FolderBrowserDialog imageFolderSelection = new FolderBrowserDialog();
imageFolderSelection.ShowDialog();
imagePath.Text = imageFolderSelection.SelectedPath;
}
private void renderButton_Click(object sender, EventArgs e)
{
string imageSavePath = imagePath.Text;
string scene = sceneFile.Text;
try
{
if (FirstFrameTextbox.Text != "" && LastFrameTextBox.Text != "") // if the textboxes are filled in then assign them to a variable
{
firstFrame = Convert.ToInt32(FirstFrameTextbox.Text);
lastFrame = Convert.ToInt32(LastFrameTextBox.Text);
if (File.Exists(scene))
{
if (File.Exists(batchFile))
{
currentFrame = firstFrame;
progressMessage.Text = " Rendering Frame " + currentFrame + " of " + lastFrame + " from " + scene;
Render();
}
else
{
File.Create(batchFile); // if there is no batch file then we make one!
currentFrame = firstFrame;
progressMessage.Text = " Rendering Frame " + currentFrame + " of " + lastFrame + " from " + scene;
Render();
}
}
else // if there is not a scene file we let the user know that
{
MessageBox.Show("Please fill in image path, project path and scene file", "Cannot find file");
progressMessage.Text = " ERROR! SCENE FILE OR IMAGE PATH IS MISSING";
}
}
else
{
MessageBox.Show("The numbers entered into the first or last frame fields are invalid", "invalid frame range");
}
}
catch (Exception f)
{
MessageBox.Show(f.ToString() + " Most commonly errors result non numerical input in the frame entry fields", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
private void ChangeRenderPath_Click(object sender, EventArgs e)
{
OpenFileDialog renderfinder = new OpenFileDialog();
renderfinder.Title = "Browse to your Render.exe file";
renderfinder.RestoreDirectory = true;
if (renderfinder.ShowDialog() == DialogResult.OK)
{
StreamWriter preferences = new StreamWriter(prefFile);
renderPathField.Text = renderfinder.FileName;
preferences.Write(renderPathField.Text);
preferences.Close();
}
}
public bool IsRendering(string processName)
{
foreach (Process renderProcess in Process.GetProcesses())
{
if (renderProcess.ProcessName.Contains(processName))
{
return true;
}
}
return false;
}
void Render()
{
while (currentFrame <= lastFrame)
{
bool rendering = IsRendering("cmd");
if (rendering == false)
{
StreamWriter renderBatch = new StreamWriter(batchFile);
renderBatch.Write('"' + renderPathField.Text + '"' + " -rd " + '"' + imagePath.Text + '"' + " -s " + currentFrame + " -e " + currentFrame + " " + '"' + sceneFile.Text + '"');
renderBatch.Close();
var renderProcess = new Process();
renderProcess.StartInfo = new ProcessStartInfo(batchFile);
//renderProcess.StartInfo.Arguments = '"' + renderPathField.Text + '"' + " -rd " + '"' + imagePath.Text + '"' + " -s " + currentFrame + " -e " + currentFrame + " " + '"' + sceneFile.Text + '"';
renderProcess.StartInfo.UseShellExecute = false;
//renderProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
renderProcess.Start();
if (renderProcess.HasExited == true && currentFrame < lastFrame)
{
ProgressBar1.Value = (currentFrame - 1) / lastFrame;
currentFrame++; //goes onto the next frame once it is done rendering this frame
}
}
}
}
private void Form1_FormClosing_1(object sender, FormClosingEventArgs e)
{
if (DialogResult.No == MessageBox.Show("If this program is not open it will not assign renders. Would you still like to close?", "You are about to stop rendering!", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation))
{
e.Cancel = true;
}
else
{
foreach (Process renderProcess in Process.GetProcesses())
{
if (renderProcess.ProcessName.Contains("cmd"))
{
renderProcess.Kill();
}
}
}
}
} // form closing brace
}
UI updates need to happen on a different thread than the main process, otherwise it will wait until the entire process is complete before showing you the updated UI.
Since you have a lot of "process" code inside your form there's not a simple fix - you will need to start the processing in another thread and set up events to pass updates back to the UI.

Categories