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 5 years ago.
Improve this question
im making an application loader which will allow you do have as many applications as you want saved in it, say for example you want to have Google Chrome in it, you press "add application" and you get an OpenFileDialog to select Chrome or any other app/program you want. the program then saves the path and name in .bin files and should load it when you click the button. it successfully loads websites but not applications, and the reason for that i think is that the program saves the file paths as
C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
instead of
C:/Program Files (x86)/Google/Chrome/Application/chrome.exe
at least thats what i think. anyway here's the code for "save" and "load":
Save:
if (metroTextBox1.Text == "" || metroTextBox2.Text == "")
{
MessageBox.Show("You have to fill in both Name and Path first", "Invalid Info", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
string[] name = { metroTextBox1.Text };
string[] path = { metroTextBox2.Text };
System.IO.File.WriteAllLines(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/appLoader/apps/appname1.bin", name);
System.IO.File.WriteAllLines(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/appLoader/apps/apppath1.bin", path);
}
Load:
try
{
string path = System.IO.File.ReadAllText(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "/appLoader/apps/apppath1.bin");
Process.Start(path);
}
catch
{
}
Process.Start() can handle both, you don't have to convert any slashes or backslashes. Starting processes like this should work fine.
To hunt down the error, please check if the file exists (File.Exists(path)), if it can be run by you in Windows directly and of course (and most important) don't just catch the exception like you did but include the thrown exception like this:
catch (Exception ex) // <-- !!
{
// investigate (and log) the exception here.
// note that catching all exceptions is not a good idea so narrow
// it down once you found the exceptions you have to care for.
}
Probably the file does simply not exist or cannot be run without having a working path set (this can be mandatory for some applications).
Related
UPDATE
try
{
//Attemps string conversion for each of the point's variables
int.TryParse(row[0], out q.pointID); //Checks for existence of data on the line...
float.TryParse(row[1], out q.xValue); //Input x-value
float.TryParse(row[2], out q.yValue); //Input y-value
float.TryParse(row[3], out q.zValue); //Input z-value
float.TryParse(row[4], out q.tempValue); //Input temp-value
}
catch (IndexOutOfRangeException)
{
Debug.Log("File out of range...");
errorLogScript.errorCode = 1100;
SceneManager.LoadScene(4);
}
This is the current code that I have but it seems to be freezing whenever I attempt to transfer the scene to the errorScreen. That being said, I am not getting an error but my code is freezing and Unity crashes whenever I attempt to test this bug.
Does anyone have any ideas on how I can fix this?
OP
I am currently working on an application in Unity and I wanted to create a bug/crash-reporting system that shows the user a unique error code upon a failure to load. Being that this specific application will be used by many people with many different skill-sets, I wanted to break it as much as I can before I release it later this year. In doing so I wanted to make a quick reference that the user will be able to look up in the documentation.
The following code demostrates what happens if the user-input filepath does not exist...
if (File.Exists(dropDownMenuScript.dataFileName + ".csv"))
{
Debug.Log("File found, loading..."); //Debugs success to console
}
else
{
Debug.Log("File not found, aborting..."); //Debugs the problem to console
errorLogScript.errorCode = 1000; //Shows the code "E1000"
SceneManager.LoadScene(4); //Loads the error-screen which displays the code
}
I recently found another error that reads; "IndexOutOfRangeException" -- in this case this pertains to the parsing of the file, meaning it exists but it does not conform to the data format compatible with the program. I would like to create another error-log for this problem but I do know how to do this as it is a Unity Editor error.
I apologize if this isn't crystal-clear, but I will provide any context needed if you need it. Thanks!
Can't you use a try-catch block and specifically traps for IndexOutOfRangeException?
try
{
//Your code...
}
catch(IndexOutOfRangeException iore)
{
//Log here
}
I try to create a sub-application that copies the database to the user desired location. Although an error is popping up that my newly created folder is being used by another application (i havent used any stream readers).
The files are correct and the copy to the selected directory is totaly working , although the problem starts when i create the folder and after i try to use him.
//Snippet
string SourceFile1 = #"C:\Users\user\Documents\DLLTESTBASE.mdf";
string SourceFile2 = #"C:\Users\user\Documents\DLLTESTBASE_log.ldf";
string BackupDirectory = BackupLocation.SelectedPath + "\\" + BackupName;
if (!Directory.Exists(BackupDirectory)){
Directory.CreateDirectory(BackupDirectory);
}
else{
MessageBox.Show("A copy has been found :\n" + BackupDirectory , "Copy has been stoped!");
}
string targetPath1 = BackupDirectory + "\\DB.mdf";
string targetPath2 = BackupDirectory + "\\DB_log.ldf";
try{
System.IO.File.Copy(SourceFile1, targetPath1);
System.IO.File.Copy(SourceFile2, targetPath2);
MessageBox.Show("Copy has been successful.", "Completed!");
}
catch (Exception ex){
MessageBox.Show("An error has been occured."+ex,"Operation failed!");}
}
The result must be that the 2 files will be inside of the folder.
Sql Data Base File in use with Sql Service
Goto Services
Stop "Sql Server" Service
you can use this link stop-or-start-sql-server-service
If u dont want to stop service use this link
Also u can use Attaching-and-Detach DB PragmaticallyAttaching-and-Detach
Try the following line before you create the files:
File.SetAttribute(targetpath1, FileAttribute.Normal);
You will get an exception thrown if the files already exist.
You will need to either delete the files and then write to them or use overwrite parameter:
System.IO.File.Copy(sourcefile1, targetPath1, true);
Sorry for late responce, as it seem the problem was occuring beacause of a hidden compartment of my main application, the problem solved after restarting my computer and reappeared when i runned the main application so you were right guys that sql file-connection was running (although it wasnt visible).
Thank you everyone for the help ☺
I asked a question yesterday, and recieved great help (especially from #AviTurner).
I have further developed the program I was working on yesterday, and I have encountered a new problem.
The code of my program can be found here.
Basicly what it does, is:
The user can select a path of a directory, and the program scans all files for read-only attribute.
It sets the read-only attribute on those files that does not currently have it.
Now the problem occurs, when it encounters a file that is currently in use (such as system files).
I have been told there is no way around this, but I thought:
Is there a way to ignore the error (by this I mean continue the program, just skip this file); and add the name of the file to a list for later tracking purposes?
I hope I made my problem clear.
Thanks.
try surrounding your code in try/catch:
try
{
System.IO.FileAttributes attr = System.IO.File.GetAttributes(file);
}
catch(Exception ex)
{
files.add(file)
}
basically if you get an exception in the try block, the program executes the catch block
I suggest...
try
{
System.IO.File.SetAttributes(file, attr);
}
catch // You can specify a specific error with catch(UnauthorizedAccessException ex) for instance.
{
filesInError.Add(file); // A list<string>() to keep track of errors.
}
Here the details, and exceptions raised, by the SetAttributes().
SetAttributes on MSDN
And some explanations about try catch if you're not familiar with.
try ... catch on MSDN
System.IO.File.Exists(string path)
returns always false, even when the file exists on the specified path. What could be the possible solution?
It could well be a permission problem. From the documentation:
The Exists method returns false if any error occurs while trying to determine if the specified file exists. This can occur in situations that raise exceptions such as passing a file name with invalid characters or too many characters, a failing or missing disk, or if the caller does not have permission to read the file.
One way of seeing what's happening is to just try to read the file (e.g. with File.OpenRead). I'd be surprised if that succeeds - but if it fails, the exception should give you more information.
Hiding file endings in windows can sometimes cause confusion: you KNOW your file is named file.txt when it is actually named file.txt.txt because the last 4 characters have been hidden by the OS.
One possibility not mentioned in any of the answers here is 'File System Redirection' on Windows 8.1 onward.
For example, if your program is a 32-bit application and you're running on 64-bit Windows then an attempt to access %windir%\System32 would be redirected to %windir%\SysWOW64. And if the file you're trying to access doesn't exist in %windir%\SysWOW64 then System.IO.File.Exists(string path) would return False.
Link to a nice article explaining this behavior
I was puzzling over this as well, then realized I was using File.Exists when I should have been using Directory.Exists.
in my case, a different "dash" in file name causes the issue.
var f1 = "4-37R.pdf";
var f2 = "4‐37R.pdf";
var r = f1==f2?"same":"diff";
Console.Write(r); //diff
turns out
var c1 = '-';
var c2 = '‐';
Console.WriteLine((int)c1); //45
Console.WriteLine((int)c2); //8208
use the same '-' fixes the issue.
How I got around this was using Server.MapPath(fileName) as it kept trying to find the file somewhere else.
System.IO.File.Exists(Server.MapPath(string path))
This had me stumped for a while while I was debugging a service locally, I was running File.Exists("U:\dir1") against a server location mapped on my workstation as (U:). I replaced the U:\dir1 to "\\serverPath\dir1" and File.Exists then returned true.
I was experiencing this myself too. In my case, I was deleting the file and re-creating it. In the process that was deleting the file, I forgot to add in WaitForExit() before using File.Exists later on
I just learned today that System.IO.File.Exists will return false if the file exists but is empty
System.IO.File.Exists(string path) returned false for me while trying to read C:\OpenSSL\bin\file.txt.
Running the application in Administrator mode did not help.
(I was logged on the administrator account, Windows 10)
Once I moved the file to C:\Users\MyUser\Desktop\file.txt, File.Exists() returned true.
Here's one more, which took me far too long to twig to.
The file name was in a constructed variable that was use to write the file, then the same variable used to check that it had been successfully written, so it could not have been different versions of '-'. I am running mono on Linux and debugging as a different user than the program is normally run by/as. Many of these types of errors are related to permissions and I spent a while banging my head on that. When File.OpenRead also threw "file not found" I finally noticed my file name had a space character at the end. I only saw this when I copied the exception message, which showed quote marks around the file name string, revealing the included space.
Apparently you can write a file name with a trailing space, but File.Exists trims that off and doesn't recognize it. When I eliminated the trailing space File.Exists worked as expected.
There can be requirement to use the DirectoryProvider Refresh() process to get the correct result from the Exists function.
e.g. code as per:
private DirectoryInfo CreateDirectory(string folderPath, int code, string message)
{
DirectoryInfo di;
try
{
di = DirectoryProvider.CreateDirectory(folderPath);
}
catch
{
throw new WebServiceException(code, HttpStatusCode.BadRequest, message);
}
di.Refresh();
if (!DirectoryProvider.Exists(di))
{
throw new WebServiceException(code, HttpStatusCode.BadRequest, message);
}
return di;
}
I was using System.IO.Path.Combine and assuming it would remove any trailing white space. For the life of me I could figure out why System.IO.File.Exists(path) was returning false.
I used the below snippet to test why it was failing
Turns out that a trailing white space was introduced causing an
"The filename, directory name, or volume label syntax is incorrect inside batch"
Hopefully someone will avoid the same stupid mistake as me
bool FileExists(string path){
try
{
using var stream = File.Open(path, FileMode.Open);
return true;
}
catch (FileNotFoundException)
{
return false;
}
catch (DirectoryNotFoundException)
{
return false;
}
catch (UnauthorizedAccessException ex)
{
Console.WriteLine(ex.message);
throw;
}
catch (Exception ex)
{
Console.WriteLine(ex.message);
throw;
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I want to run a batch file on server side in asp.net, I used the following command to execute the batch file. It's working fine when it's running in debug mode, but when I host the URL and call the batch file, it is not working.
protected void Button1_Click(object sender, EventArgs e)
{
try
{
if (FileUpload1.FileName == "")
{
Label1.Visible = true;
Label1.Text = "Browse Respective text file";
return;
}
if ((File.Exists(Server.MapPath("~/DND_BASE/" + FileUpload1.FileName))) == true)
{
Label1.Visible = true;
Label1.Text = "File Name already Uploaded";
return;
}
else
{
string DestFilepath = #"D:\124_SMS_DATA\124_SMS_Base\"+FileUpload1.FileName;
string SrcFilepath = Server.MapPath("~/DND_BASE/") + FileUpload1.FileName;
FileUpload1.SaveAs(System.IO.Path.Combine(Server.MapPath("~/DND_BASE/"), FileUpload1.FileName));
if (File.Exists(DestFilepath))
{
File.Delete(DestFilepath);
}
File.Move(SrcFilepath, DestFilepath);
Label5.Visible = true;
Label5.Text = "File Uploaded Successfully You can download file after 5 Mins";
string path = Server.MapPath(".") + "\\test.bat";
System.Diagnostics.Process.Start(path);
}
}
catch(Exception ex)
{
err = new ErrorHandler();
err.WriteToErrorLog(ex.Message.ToString());
}
}
You shouldn't run a batch file in ASP, because it runs under the permissions of the ASP user when its on a server(which for obiouse reasons is very limited) .
Your best bet is to create a scheduled job on the asp server that runs every so often and checks a folder or file that your ASP page creates or changes and then fire off events from that.
I'm not entirely sure of your goal, but please keep this in mind- The batch will run on the Local Machine. If you intend to run remotely, I'd look into Powershell. Also you will encounter several permission issues. Several batch request will require elevated permissions. Otherwise the proper way to execute a batch file from C# is like so:
using (Process.Start(#"C:\Batch\File\Location\AndName.bat"))
{
// Additional Requirements / Manipulation if Required.
}
This way it will actually dispose of the resources once your batch completes. The other alternative would be to attempt to execute the batch with elevated permissions. As I stated though before, you really should utilize Powershell as it will have access to the Windows Management Interface (WMI).
Also if you are sure about the whole batch then you'll really want to ensure you test Permissions very thoroughly. Otherwise you may encounter large errors- So familiarizing yourself with the User Access Control and ensure your Client can invoke a service to run that batch to your given machine. Be aware that you are exposing potential security issues if your data becomes malformed- As you could allow someone to alter the request to run an elevated script that is malicious.
Hopefully that at least helps.