Process won't start in ASP.NET C# - c#

So, I have a simple screen that registers the saves made in various text files (this is what I call "escenario". I can haveseveral escenarios for the important changes made to the files, and later on, if I want to return to a past escenario, I just load the files I saved. That works great, but my problem is when I try to start the process of the .exe for the python code that makes the copies of the files.
protected void AddItem(object sender, EventArgs e)
{
int num = 0;
int totalItems = escenario_list.Items.Count;
if (totalItems > 0){
string esc = "Escenario ";
num = totalItems + 1;
var x = esc + num.ToString();
var date = DateTime.Now.ToString();
var str = x + " - " + date;
escenario_list.Items.Add(new ListItem(str, num.ToString()));
Process.Start(#"C:\inetpub\wwwroot\AdministracionEscenarios\bin\MoveFiles\MoveFiles.exe");
}
else if(totalItems == 0){
string esc = "Escenario ";
num = 1;
var x = esc + num.ToString();
var date = DateTime.Now.ToString();
var str = x + " - " + date;
escenario_list.Items.Add(new ListItem(str, num.ToString()));
Process.Start(#"C:\inetpub\wwwroot\AdministracionEscenarios\bin\MoveFiles\MoveFiles.exe");
}
}
So Process.Start just won't start that .exe file. What can be the reason?? I'm also using using System.Diagnostics; at the beggining, so that's not the issue here. Thanks for the help!

The issue is how you're referencing your local drive on the server. Use this method instead Path.Combine(HostingEnvironment.MapPath("~/bin/MoveFiles/"), "MoveFiles.exe"); The HostingEnvironment will reference the directory on the server. You've been referencing the customer's local directory and not the server's local directory
Also, download and launch process explorer, and go to Find and Find Handle. Run your program and search for the MoveFiles.exe file. This will ensure that your application has executed on the server.

Related

Check Files Is Exists In Folder With Timers

I need help with C#, the question is how can I check if a .txt file exists in a folder using the timer counter, if the file already exists the counter will be stopped and attached. the message that the file is available, i ask the timer to check the folder continuously if the file already exists, the timer will stop, thanks
I hope someone will help
That is my solution to your question.
DateTime DT_Start = DateTime.UtcNow;
bool FileIsFound = false;
const int ONESEC = 1000;
string Path = #"C:\Users\Schecher_1\Desktop";
string FileName = "test.txt";
while (!FileIsFound)
{
FileIsFound = Directory.EnumerateFiles(Path, FileName).Any();
Thread.Sleep(ONESEC);
}
Console.WriteLine($"The File {FileName} was found! " +
$"{Environment.NewLine}" +
$"{(DT_Start - DateTime.UtcNow).ToString("hh':'mm':'ss")} were needed!");
var isFileExists = false;
while (!isFileExists)
{
isFileExists = Directory.EnumerateFiles("directoryToSearch", "*.txt").Any();
Thread.Sleep(1000);
}
Console.WriteLine("File found!");

C# console local chat group

I'm working on a C# console application that includes a chat group. I thought I had figured it out but it doesn't seems to work... I'm a total beginner, so the way I did it was to create a folder the program fills with .txt files with the message infos (no internet included). That worked to support the user/password/options part of the program but the chat is reacting weirdly. When you enter a message, it react and shows it on screen but when someone else post it you don't see it unless you restart the app. Here's the code:
chat_group:
temp1I = Directory.GetFiles((message_folder + "\\1-Groupe"), "*", SearchOption.AllDirectories).Length;
temp1S = temp1I.ToString();
System.IO.StreamReader ChatFile = new System.IO.StreamReader(message_folder + "\\1-Groupe\\" + temp1S + ".txt");
counter = 0;
while ((temp2S = ChatFile.ReadLine()) != null)
{
switch (counter)
{
case 0:
text = (temp2S + ": ");
WRITE_R();
break;
case 1:
text = (temp2S);
WRITE();
break;
}
counter++;
}
ChatFile.Close();
Console.WriteLine("");
test:
if (File.Exists((message_folder + "\\1-Groupe\\" + (temp1S + 1) + ".txt")))
{
goto chat_group;
}
if ((temp3S = Console.ReadLine()) != null)
{
temp1S = (temp1I + 1).ToString();
string[] ChatLines2 = { username, temp3S };
System.IO.File.WriteAllLines(message_folder + "\\1-Groupe\\" + temp1S + ".txt", ChatLines2);
}
goto test;
Note: As it is a big application, I've not copy the variables but I ensure they are correct as they work on all the other parts of the app.

FileSystemWatcher DCOM Errors

Most would probably ignore this but I really need help. I am currently developing a Windows Service that uses FileSystemWatcher to monitor the changes on the web.config files on remote web servers.
What it generally does is upon initialization of the service, it gets the websites on IIS from a list of web servers defined in app.config, then puts a FileSystemWatcher on the the websites' web.config file and another file named web.config.orig.
When either the web.config or the web.config.orig file changes, it triggers the FileSystemWatcher then checks the LastModifiedDate of both files. If is not equal, it should generate an event log that says the the file's modified dates are not in sync.
The service successfully installs then I was able to test it one time, but it triggers the FileSystemWatcher a lot then generates a lot of this sort of error in the System Logs:
DCOM was unable to communicate with the computer Server1 using any of the configured protocols; requested by PID 4c08 (C:\Users\user1\Desktop\DynamicFSW\DynamicFSW\bin\Debug\DynamicFSW.exe).
You can download the source code here: https://www.dropbox.com/s/1pkh543g5n578fy/DynamicFSW.rar?dl=0
private void file_OnChanged(object sender, FileSystemEventArgs e)
{
FileSystemWatcher fsw = (FileSystemWatcher)sender;
try
{
fsw.EnableRaisingEvents = false;
string directory = Path.GetDirectoryName(e.FullPath);
string webconfig = directory + "\\web.config";
string webconfigorig = directory + "\\web.config.orig";
DateTime dt1 = File.GetLastWriteTime(webconfig);
DateTime dt2 = File.GetLastWriteTime(webconfigorig);
DynamicFSWEventLog.WriteEntry("" + e.FullPath);
string server = "";
for (int i = 2; i < directory.Length; i++)
{
if (directory[i] != '\\')
{
server += directory[i];
}
else
{
break;
}
}
DynamicFSWEventLog.WriteEntry("" + server);
if (!System.DateTime.Equals(dt1, dt2))
{
ServerManager IIS = Microsoft.Web.Administration.ServerManager.OpenRemote(server);
foreach (Site site in IIS.Sites)
{
if (Path.GetDirectoryName(e.FullPath).Equals("\\\\" + server + "\\" + site.Applications["/"].VirtualDirectories[0].PhysicalPath.Replace(':', '$')))
{
string message = "Server: " + server + "\n" +
"Website: " + site.Name + "\n" +
"Web.config.LastWriteTime: " + dt1 + "\n" +
"Web.config.orig.LastWriteTime: " + dt2 + "\n\n" +
"Web.config and Web.config.orig file's last write time not in sync!";
DynamicFSWEventLog.WriteEntry("" + message);
}
}
}
}
finally
{
fsw.EnableRaisingEvents = true;
}
}
I would really appreciate anyone's help on this.
Thanks!

C# - How do I create a txt file in memory and then open it programatically?

I'm having a problem creating a txt file on C#. I am trying to create this file in memory (I don't want to create it in a physical path) and then open this file programmatically with the defaul app. The PC must detect the file extension (in this case .txt) and choose the right program to display the file (in this case maybe Notepad, Word, Wordpad...).
I got this now:
using (var writer = new StreamWriter("file.txt"))
{
writer.WriteLine(
grr[0].Keys.ToArray()[0] + "," + grr[0].Keys.ToArray()[1] + "," +
grr[0].Keys.ToArray()[2] + "," + grr[0].Keys.ToArray()[3]);
for (int r = 0; r < row - 1; r++)
{
writer.WriteLine(
grr[r].Values.ToArray()[0] + "," + grr[r].Values.ToArray()[1] + "," +
grr[r].Values.ToArray()[2] + "," + grr[r].Values.ToArray()[3]);
}
}
But I don't know how to open this file.
You want a file system in memory that contains filename and data. So use something like this:
public class MyFolder
{
string folderName { get; set;}
List<MyFolder> childFolders { get; set; }
Dictionary<string, List<byte>> files { get; set; }
}
Ok, the only solution I see is quite a hack:
Write the data on a file;
Open the file with the default app using Process.Start;
Delete the file with File.Delete.
Code:
// test data that I'll write on the file
var text = Enumerable.Range(0, 1000000).Select(x => x.ToString()).ToArray();
// choose the Desktop folder to verify that
// the file is deleted at the end of the method
var tempDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
// choose a random file name that will be unique 99.999999999% of the times
var filePath = Path.Combine(tempDir, Guid.NewGuid().ToString() + ".txt");
// write the file. Here I use WriteAllLines, you can use StreamWriter
File.WriteAllLines(filePath, text);
// start the default app for this path
Process.Start(filePath);
// wait to let the default app to open the file;
// otherwise the app will crash, not finding the file anymore
// just in the middle of the read
// (I put 2 sec, but the time must be verified
// depending on your system and the file size)
Thread.Sleep(2000);
// this will totally delete the file
File.Delete(filePath);
If you have Notepad as default app for txt files, that's what you'll see: Notepad opens up with your data, but the file doesn't exist anymore. That's quite what you wanted, isn't it? You won't find the file in the Recycle Bin neither, so you won't have disk space leaks.
The only defect of this trick is: if you click "Save" on your app, it won't ask you the path where you want to save the file. Instead, it will simply re-create the file as it was before deletion, and will save the data directly. That's because it opened a physical file, it didn't created a new one, so it remembers the filePath and will use it to save.
If you don't find more correct/professional solutions, this one can do its job.
ASIDE:
I'd suggest to you a little refactoring.
First step, avoid repetitions:
using (var writer = new StreamWriter("file.txt"))
{
var array = grr[0].Keys.ToArray();
writer.WriteLine(array[0] + "," + array[1] + "," + array[2] + "," + array[3]);
for (int r = 0; r < row - 1; r++)
{
var grrr = grr[r].Values.ToArray();
writer.WriteLine(grrr[0] + "," + grrr[1] + "," + grrr[2] + "," + grrr[3]);
}
}
Second step, use more advanced built-in functions:
using (var writer = new StreamWriter("file.txt"))
{
writer.WriteLine(string.Join(",", grr[0].Keys.ToArray()));
for (int r = 0; r < row - 1; r++)
{
writer.WriteLine(string.Join(",", grr[r].Values.ToArray()));
}
}

C# - setting a user defined folder path as a string variable the first time a program is run

Thanks to you all for the help so far! I am extremely new to c# and code in general. I have a question that I cannot seem to find the answer to.
I just wrote a simple program that moves files from one folder to a new folder named that day's date. Please see below:
private void button1_Click(object sender, EventArgs e)
{
DateTime now = DateTime.Now;
string date = (now.ToString("D"));
string a = #"m:\\staff docs\\faxes\\";
string b = #a + date + "\\";
System.IO.Directory.CreateDirectory(b);
DirectoryInfo dir1 = new DirectoryInfo("c:\\blah");
DirectoryInfo dir2 = new DirectoryInfo("#b");
FileInfo[] DispatchFiles = dir1.GetFiles();
if (DispatchFiles.Length > 0)
{
foreach (FileInfo aFile in DispatchFiles)
{
string files = #b + aFile.Name;
int count = 0;
Find :
if (File.Exists(files))
{
files = files + "(" + count.ToString() + ").txt";
count++;
goto Find;
}
aFile.MoveTo(files);
}
}
{
MessageBox.Show("Your files have been moved!");
I'd like to have the user define the source folder variable and the destination folder variable, either by having them navigate to the folder in a file browser, or a Console.ReadLine - but not every time they run the program, just the first. It would be ideal if they could change the path if they wanted to later on as well.
Many thanks!
EDIT
My solution was a Button on my Form that calls this block:
private void button3_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.Description = "Select source folder";
fbd.ShowDialog();
string Source = fbd.SelectedPath;
Properties.Settings.Default.source = Source;
Properties.Settings.Default.Save();
FolderBrowserDialog fbd2 = new FolderBrowserDialog();
fbd2.Description = "Select destination folder";
fbd2.ShowDialog();
string d1 = fbd2.SelectedPath;
string d2 = "\\";
string Destination = d1 + d2;
Properties.Settings.Default.destination = Destination;
Properties.Settings.Default.Save();
}
you can use the "user settings" described here: http://msdn.microsoft.com/en-us/library/bb397750.aspx
//EDIT:
let's say You have a USER Setting of type string called "MySetting"
if you want to read it:
var someVar = Properties.Settings.Default.MySetting;
if you want to write it (assuming your data is in someVar):
Properties.Settings.Default.MySetting = someVar;
Properties.Settings.Default.Save();
the call to Save() persists your changes ... the changes are bound to the windows user account
at design time your setting should be defined as Scope USER
There are a few possibilities you can use.
One thing would be to create an XML-file the first time the user entered the paths. You could check for the existance of the file and if it exists, read from it and if not exists, create it and write data to it. Of course you are capable of editing your XML-file.
There is the System.Xml.XmlDocument-class
using System;
using System.IO;
using System.Xml;
public class Sample
{
public static void Main()
{
string inputpath = "C:\....";
//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
//Create a new node and add it to the document.
//The text node is the content of the price element.
XmlElement elem = doc.CreateElement("Inputpath");
XmlText text = doc.CreateTextNode(inputpath);
doc.DocumentElement.AppendChild(elem);
doc.DocumentElement.LastChild.AppendChild(text);
doc.Save(Console.Out);
}
}
See here for a reference.
You could write a value into the registry, too. Just as a possibility.

Categories