Copy file to newly created directories - c#

So I have a bit complicated one, I'm trying to create a "template creator". User will input data via comboboxes and textboxes into a form, from which a button generates the names (combination of inputs). After that next button creates directories as required. Until this point everything is ok, however, after this, I prompted a question whether the user wants to start copying files to the newly created directories.
Current code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.VisualBasic;
namespace ME_Nitra_BIW_App
{
public partial class ToolingDesign : Form
{
// create folder path to enable new folder creation
private void btnGenerateFilePath_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
tBoxFilePath.Text = folderBrowserDialog1.SelectedPath;
btnCreateDir.Enabled = true;
}
private void btnCreateDir_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(tBoxFilePath.Text))
{
System.Windows.Forms.MessageBox.Show("No file path selected!");
}
else
{
// for Assembly folder
string fileNameAssy = "FIXED_PARTS_PRODUCT.CATProduct";
string sourcePathAssy = #"c:\Users\mjanus\Downloads\CATIAV5\START_MODELS\CAT_PRODUCTS";
string targetPathAssy = tBoxFilePath.Text + #"\" + tBoxFolderName.Text + #"\" + tBoxFolderName.Text + "_U000" + "_ASSEMBLY";
// use path class to manipulate file and directory paths
string sourceFile = System.IO.Path.Combine(sourcePathAssy, fileNameAssy);
string destFile = System.IO.Path.Combine(targetPathAssy, fileNameAssy);
string dirPath = tBoxFilePath.Text + #"\" + tBoxFolderName.Text + #"\" + tBoxFolderName.Text;
// create new folders with generated names
btnGenerateFilePath.Enabled = false;
btnCreateDir.Enabled = false;
Directory.CreateDirectory(tBoxFilePath.Text + #"\" + tBoxFolderName.Text);
System.Threading.Thread.Sleep(500);
Directory.CreateDirectory(dirPath + "_U000" + "_ASSEMBLY");
Directory.CreateDirectory(dirPath + "_U001" + "_PRODUCT_PARTS");
Directory.CreateDirectory(dirPath + "_U002" + "_CLAMP_STUDY");
Directory.CreateDirectory(dirPath + "_U003" + "_GUN_STUDY");
Directory.CreateDirectory(dirPath + "_U004" + "_PRODUCT_PARTS");
Directory.CreateDirectory(dirPath + "_U005" + "_MECHANICAL_SEQUENCES");
Directory.CreateDirectory(dirPath + "_U006" + "_MISCELLANEOUS");
Directory.CreateDirectory(dirPath + "_U007" + "_SUPPORT");
// ask if user wants to copy template files to the newly created folders
DialogResult dialogResult = MessageBox.Show("Directories successfuly created!" + Environment.NewLine + "Do you wish to copy files now?", "Success!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
// if the directory folder already exists, this method does not create a new directory
System.IO.Directory.CreateDirectory(targetPathAssy);
// overwrite the destination file if it already exists
System.IO.File.Copy(sourceFile, destFile, true);
// start of copy
if (System.IO.Directory.Exists(sourcePathAssy))
{
string[] files = System.IO.Directory.GetFiles(sourcePathAssy);
foreach (string s in files)
{
fileNameAssy = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPathAssy, fileNameAssy);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
MessageBox.Show("Source path does not exist!");
}
}
else if (dialogResult == DialogResult.No)
{
this.Close();
}
}
}
}
As you can see I've set the targetPathAssy to the same location as what the new folder is created, but I'm not sure if the code can read that? Or how could I store that newly created directory path and call it?

I found the solution, and it's much simpler than what I've tried before.
Here's the full code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using Microsoft.VisualBasic;
namespace ME_Nitra_BIW_App
{
public partial class ToolingDesign : Form
{
public ToolingDesign()
{
InitializeComponent();
radioButton1.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
radioButton2.CheckedChanged += new EventHandler(radioButton_CheckedChanged);
}
private void btnCreateDir_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(tBoxFilePath.Text))
{
System.Windows.Forms.MessageBox.Show("No file path selected!");
}
else
{
// directory path
string dirPath = tBoxFilePath.Text + #"\" + tBoxFolderName.Text + #"\" + tBoxFolderName.Text;
// where to paste the files
string targetPathAssy = dirPath + "_U000" + "_ASSEMBLY";
// create new folders with generated names
btnGenerateFilePath.Enabled = false;
btnCreateDir.Enabled = false;
Directory.CreateDirectory(tBoxFilePath.Text + #"\" + tBoxFolderName.Text);
System.Threading.Thread.Sleep(500);
Directory.CreateDirectory(dirPath + "_U000" + "_ASSEMBLY");
Directory.CreateDirectory(dirPath + "_U001" + "_PRODUCT_PARTS");
Directory.CreateDirectory(dirPath + "_U002" + "_CLAMP_STUDY");
Directory.CreateDirectory(dirPath + "_U003" + "_GUN_STUDY");
Directory.CreateDirectory(dirPath + "_U004" + "_PRODUCT_PARTS");
Directory.CreateDirectory(dirPath + "_U005" + "_MECHANICAL_SEQUENCES");
Directory.CreateDirectory(dirPath + "_U006" + "_MISCELLANEOUS");
Directory.CreateDirectory(dirPath + "_U007" + "_SUPPORT");
// ask if user wants to copy template files to the newly created folders
DialogResult dialogResult = MessageBox.Show("Directories successfuly created!" + Environment.NewLine + "Do you wish to copy files now?", "Success!", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
// test copy
File.Copy(#"Resources\UNIT_START_PRODUCT.CATProduct", targetPathAssy + #"\" + "UNIT_START_PRODUCT.CATProduct");
}
else if (dialogResult == DialogResult.No)
{
this.Close();
}
}
}
// create folder path to enable new folder creation
private void btnGenerateFilePath_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
tBoxFilePath.Text = folderBrowserDialog1.SelectedPath;
btnCreateDir.Enabled = true;
}
}
}
The change:
Turns out that I can use the same string to copy the file to the newly created directory which uses the string dirPath as shown above. Although I've embedded the files into the application (ease of use, not sure if I would get a dedicated folder on the server) I've used the
File.Copy(#"Resources\UNIT_START_PRODUCT.CATProduct", targetPathAssy + #"\" + "UNIT_START_PRODUCT.CATProduct");
I had to add the #"\" because otherwise the copied file would have the targetPathAssy added to its name instead of going into the specific folder.
Hope this helps someone in the future

Related

C# Update Table Button Not Working Automatically

I have some c# code and recently I added a button to the form designer which runs a simple update table query (update a SQL table). The table is updated as I would expect when I manually click the button in Debug mode, however when I run the entire program, it appears the method/button to update the SQL table is either ignored or simply not being picked up. As I mentioned, this works fine when I go into Debug and click on the button manually, however what I need it to do is run the method and click the button automatically as it is doing for the other methods. I have gone through this hundreds of times and am at the end of the road. Below is my code;
private void updateClosedModuleState()
{
System.Data.SqlClient.SqlConnection saConn = new System.Data.SqlClient.SqlConnection();
saConn.ConnectionString = GlobalDef.strSQLConnection;
//MessageBox.Show(saConn.ConnectionString);
try
{
saConn.Open();
SqlCommand command = saConn.CreateCommand();
command.CommandTimeout = saConn.ConnectionTimeout;
command.CommandType = System.Data.CommandType.Text;
command.CommandText = " UPDATE SATA_AllocationObject "
+ " SET State = REPLACE(State, 'A', 'I') "
+ " where AllocationObjectType = 4 "
+ " and Hostkey in (select hostkey from TRAN_UnitEClosedModules)";
command.ExecuteNonQuery();
}
catch (Exception act)
{
MessageBox.Show("Ooops! Error " + act.Message.ToString() + " when updating Module State");
}
finally
{
saConn.Close();
}
pictureBox19.Visible = true;
}
This is the code for the button click;
private void cmdUpdateClosedModuleState_Click(object sender, EventArgs e)
{
updateClosedModuleState();
}
Lastly, these are the method details in the form designer;
this.cmdUpdateClosedModuleState.Location = new System.Drawing.Point(517, 114);
this.cmdUpdateClosedModuleState.Name = "cmdUpdateClosedModuleState";
this.cmdUpdateClosedModuleState.Size = new System.Drawing.Size(107, 23);
this.cmdUpdateClosedModuleState.TabIndex = 41;
this.cmdUpdateClosedModuleState.Text = "UpdateModState";
this.cmdUpdateClosedModuleState.UseVisualStyleBackColor = true;
this.cmdUpdateClosedModuleState.Click += new System.EventHandler(this.cmdUpdateClosedModuleState_Click);
I have also tried to use a TableAdapter and use a Fill to update the SQL Table via the button, and that works...only when I click the button in Debug mode;
private void newupdate()
{
//throw new NotImplementedException();
this.sATA_AllocationObject1TableAdapter.Fill(this.moduleSignupTestDataSet.SATA_AllocationObject1);
}
I assigned a buttton to run the Fill on the TableAdapter;
private void newupdate_Click(object sender, EventArgs e)
{
//this.sATA_AllocationObject1TableAdapter.Fill(this.moduleSignupTestDataSet.SATA_AllocationObject1);
newupdate();
}
So in a nutshell, I need the program to run this method like it does with all the other ones without my intervention.
I have attached a photo of the form - when I click 'Run All' everything runs except for the UpdateClosedModState; [1]: https://i.stack.imgur.com/dJryA.png
The code behind the Run All command is;
private void cmdRunAll_Click(object sender, EventArgs e)
{
begin();
}
In the form designer we have;
this.cmdRunAll.Location = new System.Drawing.Point(381, 375);
this.cmdRunAll.Name = "cmdRunAll";
this.cmdRunAll.Size = new System.Drawing.Size(107, 21);
this.cmdRunAll.TabIndex = 10;
this.cmdRunAll.Text = "Run All";
this.cmdRunAll.UseVisualStyleBackColor = true;
this.cmdRunAll.Click += new System.EventHandler(this.cmdRunAll_Click);
And at the start of the form, we have this to begin running the app;
if (args.Length > 0)
{
lArgsExists = true;
// strDetails = strDetails + ": About to run app.";
// runApp(args[0], lArgsExists);
begin();
}
}
public void runApp(string cnfgPath, bool gui)
{
if (gui == true)
{
strDetails = strDetails + " Running app.";
begin();
}
else
{
textBox2.Text = GlobalDef.appStatus.ToString();
begin();
//MessageBox.Show("Opening form!");
}
}
public void begin()
{
String sqlServerLogin = GlobalDef.sqlServerlogin;
String password = GlobalDef.password;
String instanceName = GlobalDef.instanceName;
String remoteSvrName = GlobalDef.remoteSvrName;
string strNow = DateTime.Now.Day + "/" + DateTime.Now.Month + "/" + DateTime.Now.Year;
string strSQLConnection = GlobalDef.strSQLConnection;
textBox2.Text = GlobalDef.appStatus.ToString();
//string path = #"E:\Allocator\StudentAllocatorTest\logs\Error.log";
string path = GlobalDef.path;
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Error details");
}
}
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine();
sw.WriteLine("******************************************");
sw.WriteLine();
sw.WriteLine(strDetails.ToString());
sw.WriteLine("******************************************");
sw.WriteLine();
sw.WriteLine(DateTime.Now.ToString() + ": Starting load for " + GlobalDef.instanceName);
}
try
{
string connString = GlobalDef.connString;
OracleConnection oraCon = new OracleConnection(connString);
System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection();
conn.ConnectionString =
"data source=" + remoteSvrName + ";" +
"persist security info=true;initial catalog=" + instanceName + ";User Id=" + sqlServerLogin + "; Password=" + password + ";";
// Clear transfer tables before running any subroutine
clearTransTables();
// Loads Department details into SA TransTables
updateDepartment(oraCon, strSQLConnection);
// Loads new POSA modules into SA TransTables
updatePOSA(oraCon, strSQLConnection, path);
// Loads new POSY modules into SA TransTables
updatePOSY(oraCon, strSQLConnection, path);
// Remove open option links for modules which do not have the timetable flag checked
RemoveUnneededOOCourses(oraCon, strSQLConnection, path);
// Loads top-level OO structure into SA TransTables
OpenOption(oraCon, strSQLConnection, path);
// Loads Dept level OO structure into SA TransTables
OptionByDept(oraCon, strSQLConnection, path);
// Links OOByDept Allocation Objects to OO Objects via TransTables
linkOOAndOOByDept(path);
// Loads new Course modules into SA TransTables
updateCourse(oraCon, strSQLConnection, path);
// Links OO courses to OOByDept AllocationObjects via TransTables
OpenOptionCourses(oraCon, strSQLConnection, path);
//Adds All Courses to various hidden groups via TransTables
updateAllHidden(oraCon, strSQLConnection, path);
// Loads new students into SA TransTables
//TransferStudent(oraCon, strSQLConnection);
// Loads prerequisite allocations into SA TransTables
UploadPrerequisites(oraCon, strSQLConnection);
//button1_Click();
// Loads Closed Modules from UnitE to TRAN_UnitEClosedModules
uploadUnitEClosedModules(oraCon, strSQLConnection);
//Runs the transfer service which loads the data in the TransTables into the database
runTransferservice(path);
///
newupdate();
// update Closed Modules to 'I' State
updateClosedModuleState();
// Used to create a structure for programmes which had yet to be set up by faculties
// DefaultCourseStructure(oraCon, strSQLConnection);
// Creates UNITe course enrolments and cancels changed course selections
uploadAllocationsToUNITe(oraCon, strSQLConnection, path);
// pictureBox11.Visible = true;
}
catch (Exception e)
{
MessageBox.Show(e.Message.ToString());
}
finally
{
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine(DateTime.Now.ToString() + ": Completed load for " + GlobalDef.instanceName);
}
Application.Exit();
}
}
private void updateDepartment(OracleConnection oraCon, string strSQLConnection)
{
try
{
....and it goes on with the subroutines listed above.
Any help would be greatly appreciated.
Thank you in advance.

Try to launch an application from another application continue to crash

I wrote a program in C # that takes, from a WPF interface, a folder path, a prefix, and a prefix of substitution. The purpose of the program is to search in the folder all the files that start with the prefix and rename them with the new prefix. This program works without any problems.
Now I have to write a second program that must call the previous, passing the parameters using args []. I wrote this second program, it seems that all the parameters have passed correctly to the other (I checked it), but every time the replacement program runs out after a few seconds (while the normal run in my folder of Trial is almost instantly). I'm not able to have any message error or exception, I can only obtain the windows alert message that reports the crash.
Here is the significant part of the code of both programs ... Can anyone help me to find the problem? Is it a problem with settings passed from one program to another? Thanks a lot to everyone.
Can it maybe be a problem about the setting parameters of the calling?
Replace prefix program:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
namespace replace_prefix
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
string[] args;
args = Environment.GetCommandLineArgs();
if (args.Length > 1)
{
((MainWindow)App.Current.MainWindow).Close();
sf_textBox.Text = args[1];
rp_textBox.Text = args[2];
np_textBox.Text = args[2];
replace();
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void ok_button_Click(object sender, RoutedEventArgs e)
{
replace();
}
private void replace() {
if (sf_textBox.Text == "" || rp_textBox.Text == "" || np_textBox.Text == "")
MessageBox.Show(this, "Insert all required parameters", "Parameter missing", MessageBoxButton.OK, MessageBoxImage.Error);
else
{
using (StreamWriter w = File.CreateText("log.txt"))
{
DirectoryInfo d = new DirectoryInfo(sf_textBox.Text);
FileInfo[] Files = d.GetFiles("*.*");
string filename, log;
foreach (FileInfo file in Files)
{
filename = file.Name;
int Place = filename.IndexOf(rp_textBox.Text);
if (Place == 0)
{
log = "file " + filename + " renamed ";
filename = filename.Remove(Place, rp_textBox.Text.Length).Insert(Place, np_textBox.Text);
file.MoveTo(file.Directory.FullName + "\\" + filename);
Log(log + filename, w);
}
}
w.Close();
}
Environment.Exit(0);
}
}
public static void Log(string logMessage, TextWriter w)
{
w.Write(DateTime.Now.ToLongTimeString(), DateTime.Now.ToLongDateString());
w.Write(" --> ");
w.WriteLine(logMessage);
}
}
}
Calling method in the other program:
public void LaunchCommandLineApp()
{
using (StreamWriter wl = File.CreateText(job.name + "_log.txt"))
{
lock (wl) wl.WriteLine("\\n" + DateTime.Now.ToString() + " --> " + job.name + ": " + job.process + " launched");
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = job.process;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
var count = job.args.Count(c => c == ';');
startInfo.Arguments = "";// "-f ";
while (count > 1)
{
startInfo.Arguments += job.args.Substring(0, job.args.IndexOf(';', 0));
int i = job.args.IndexOf(';', 0) + 1, k = job.args.Length - 1;
job.args = job.args.Substring((job.args.IndexOf(';', 0) + 1), (job.args.Length - 1) - (job.args.IndexOf(';', 0)));
count--;
}
if (count == 1) {
int i = job.args.IndexOf(';', 0);
startInfo.Arguments += job.args.Substring(0, job.args.IndexOf(';', 0));
}
if (job.recurrency) job.updateRecurrency();
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
string tl;
try
{
tl = Path.GetDirectoryName(job.process);
}
catch (ArgumentException e) {
tl = null;
}
if (tl != null)
{
try
{
tl = tl + "\\log.txt";
StreamReader input = new StreamReader(tl);
tl = input.ReadLine();
while (tl != null)
{
wl.WriteLine(tl);
tl = input.ReadLine();
}
input.Close();
}
catch (Exception e) { }
}
lock (wl) wl.WriteLine(DateTime.Now.ToString() + " --> " + job.name + ": " + job.process + " successfully ended.");
}
}
catch (Exception e)
{
//add local process log
lock (wl) wl.WriteLine(DateTime.Now.ToString() + " --> " + job.name + ": " + job.process + " failed to ended. " + e.Message.ToString());
}
wl.Close();
InvokeExecutionFinished(new EventArgs());
}
//Send log via email
//sendNotification();
}
Crash report

Filesystemwatcher events

I am having a problem with some filewatcher events. The filewatcher has 4 events. Created, Changed, Deleted, Renamed. Now my Created event works fine, but the rest doesn't although the application does run the events. I made it so when the created event is activated, the file in the 1st directory will automatically be copied to the 2nd directory. And so on with the rest of the events(File in 1st directory deleted, automatically delete in the 2nd directory). Like for example, this is my Deleted Event:
private void fileSystemWatcher1_Deleted(object sender, FileSystemEventArgs e)
{
if (!pause)
{
filepath = Path.Combine(source, e.Name);
name = Path.GetFileNameWithoutExtension(filepath);
File.Delete (target + e.Name); // Delete file in directory:"target"
query = "delete from " + tablemysql + " where name='" + name + "'";
Mysql();
}
}
So when I debug it, it does run through the File.Delete (target + e.Name); but it doesn't delete the file in the second directory. The delete query is working in mysql.
At the top I defined the variable target:
String target = ConfigurationManager.AppSettings[#"Directory2"];
and in the app config:
<add key="Directory2" value="C:\Users\Loko\Desktop\Loko\3"/>
Now I dont see any difference in executing everything in the created event and the deleted event
It has to delete a file in the 2nd directory(target) when the deleted event is called.
To compare some stuff, this is my Created event which works fine:
private void fileSystemWatcher1_Created(object sender, FileSystemEventArgs e)
{
if (!pause)
{
filepath = Path.Combine(source, e.Name);
name = Path.GetFileNameWithoutExtension(filepath);
extension = Path.GetExtension(e.FullPath);
size = e.Name.Length;
readquery = "select * from " + tablemysql + " where name='" + name + "'";
Record();
query = "INSERT INTO " + tablemysql +
" (name,size,last_edit,extension) VALUES('" +
name + "','" + size + "',now(),'" + extension + "')";
Mysql();
if (Directory.Exists(e.FullPath))
{
copyfolder();
Directory.CreateDirectory(target);
}
else
{
if (WaitForFileAvailable(e.FullPath, TimeSpan.FromSeconds(30)))
{
var file = Path.Combine(source, e.Name);
var copy_file = Path.Combine(target, e.Name);
var destination = Path.Combine(target,
Path.ChangeExtension(source, Path.GetExtension(source)));
if (File.Exists(file))// Check to see if the file exists.
{
// If it does delete the file in the target and
// copy the one from the source to the target.
File.Delete(copy_file);
}
File.Copy(e.FullPath, copy_file);
}
}
}
}
What is going wrong here?
You state that your target is defined as "C:\Users\Loko\Desktop\Loko\3". Assuming your filename is "myfile.txt" (for example), then the line:
File.Delete (target + e.Name);
will be attempting to delete "C:\Users\Loko\Desktop\Loko\3myfile.txt", which is missing a path separator.
You should instead use Path.Combine.
File.Delete(Path.Combine(target, e.Name))
Remarks
You may have been expecting an exception to be thrown on the File.Delete call if the file does not exist. However, the documentation states:
If the file to be deleted does not exist, no exception is thrown.

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.

Saving a currently opened file without prompts

I am experiencing a problem with saving a currently opened file without it popping up the dialog asking what name to save it under.
To clarify myself a little more, I open a .txt file and work with it, then would like to just click 'Save' and it save the file without popping up a 'Save As' dialog box.
Here is my save code:
private void SaveFile()
{
SaveFileDialog fileChooser = new SaveFileDialog();
fileChooser.Title = "Choose Save Location";
fileChooser.Filter = "Text Files (*.txt)|*.txt";
fileChooser.OverwritePrompt = false; //Removes warning
DialogResult result = fileChooser.ShowDialog();
if (result == DialogResult.Cancel)
{
return;
}
try
{
string fileName = fileChooser.FileName;
output = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write);
fileWriter = new StreamWriter(output);
foreach (Employee emp in employee)
{
fileWriter.WriteLine(emp.Firstname + "," + emp.Lastname + "," + emp.Position + "," + emp.Bmonth + "," + emp.Bday + "," + emp.BYear + "," + emp.Salary + "," + emp.Hiremonth + "," + emp.Hireday + "," + emp.Hireyear);
}
fileWriter.Close();
output.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
fileWriter.Close();
output.Close();
}
}
Everything works great as far as saving it to a .txt file and loading it back in, it's just that popup that irks me.
The fileChooser object is a SaveFileDialog object. You're causing it to display by calling:
DialogResult result = fileChooser.ShowDialog();
If you don't want to show the dialog, just omit the fileChooser code and instead use:
string fileName = strAlreadyKnownFileName;
I'd firstly save the full path of the opened file in some variable lets say:
private string filepath = "path/to/my/file";
Then you need to create a button and call it i.e. "Save" double click on the button and write this simple code to save whatever you want to the current opened file:
as simple as that...
EDIT:
private void SaveFile()
{
//do your loop and stuff in here and finally write your text to the file using this
File.WriteAllText(filepath, yourtexttobesaved);
}

Categories