"Given Path Format Is Not Supported"... Can you help me? - c#

So, I made a speech recognizer and it was working fine, I'm not sure why is it giving me this error right now. Any ideas?
String res = e.Result.Text;
string yol = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string settings = ("#" + yol + "\\" + "settings" + "\\");
if (res == "Hi Bot")
{
pictureBox1.Image = Image.FromFile(settings + "mybot.png"); -->That's where i get the error
say(greetings_random());
}

string yol = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string settings = ("#" + yol + "\\" + "settings" + "\\");
This means that settings has the value "#C:\Path\To\Executable\settings\".
That's probably not what you want -- I'm not sure what the # is trying to achieve, but it's not valid at the beginning of a path like that.
For future, debugging this code and inspecting the settings variable would quickly have shown the problem.
That said, it's recommended to use Path.Join (.NET Core 2.1+) or Path.Combine instead of string concatenation to create paths like this.

Related

Process.GetCurrentProcess().MainWindowTitle of Revit retrieves empty string ""

I am creating a plugin for Revit that registers several events within its application.
For every time an event happens, a line is writen on a txt file telling me about the event such as:
The user opened a document on Autodesk Revit 2019 (...)
I am obtaining the "Autodesk Revit 2019" (name of application) by getting the name of the MainWindowTitle of the application like so: Process.GetCurrentProcess().MainWindowTitle
public static string originalString = Process.GetCurrentProcess().MainWindowTitle;
(...)
Trace.WriteLine("O utilizador " + Environment.UserName + " abriu o " + originalString + " a " + DateTime.Now + " (ApplicationInitializedEventArgs)");
Which writes in the txt file:
O utilizador rita.aguiar abriu o a 20/09/2018 10:36:42 (ApplicationInitializedEventArgs)
As you can read, it did not write on the txt file "Autodesk Revit 2019 - [Home]" between the words "o" and "a" as I hoped for.
If I had writen Process.GetCurrentProcess().MainWindowTitle directly on the Trace.WriteLine I would have obtained "Autodesk Revit 2019 - [Home]", but I wish to write an assigned name instead.
How to successfully write "Autodesk Revit 2019 - [Home]" by assigning a name to Process.GetCurrentProcess().MainWindowTitle?
Later I would like to obtain this name by instead getting just Autodesk Revit 2019 like so:
public static string originalString = Process.GetCurrentProcess().MainWindowTitle;
public static string[] splittedString = originalString.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
public static string AppName = splittedString[0];
Any help would be appretiated!
As I suggested answering your similar question on assigning a name to a string C# in the Revit API discussion forum, I would look at the code executing step by step in the debugger.
Then you can see for yourself exactly what is going on.
You could also add some more intermediate lines and variables for absolute clarity:
string originalString = Process
.GetCurrentProcess()
.MainWindowTitle;
string s2 = "O utilizador "
+ Environment.UserName
+ " abriu um documento no "
+ originalString + " a " + DateTime.Now;
//or use string interpolation:
//https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
string s3 = $"O utilizador {Environment.UserName} abriu um documento no {originalString} a {DateTime.Now}";
Trace.WriteLine( s2 );
Trace.WriteLine( s3 );
The debugger is good!
Invaluable, in fact.
Some of the comments on the discussion how to determine Revit demo mode show how you can access the Revit main window title.
To be able to store the Main Window Title in a name of type string I had to first declare each string outsite of the methods I am using:
string originalString;
string[] splittedString;
string AppName;
After declaring each string name I obtained the Application Name "Autodesk Revit 2019" by including each definition inside the first private method, which was created to register when the Revit application is opened. This had to be done inside a method because it is only after the application is launched that we can access the MainWindowTitle. This is the reason why I was getting an empty string "" when trying to obtain the MainWindowTitle the moment the application is starting to launch, but before it has completely launched and thus opened a Window with such Title.
private void DumpEventArgs(ApplicationInitializedEventArgs args_initialized)
{
originalString = Process.GetCurrentProcess().MainWindowTitle;
splittedString = originalString.Split(new[] { " -" }, StringSplitOptions.RemoveEmptyEntries);
AppName = splittedString[0];
//StreamWriter file = new StreamWriter("C://Users//" + Environment.UserName + "//AppData//Roaming//Autodesk//" + Environment.UserName + ".txt", append: true);
//MessageBox.Show($"O utilizador {Environment.UserName} iniciou o {AppName} a {DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")}");
file.WriteLine($"{Environment.UserName},{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")},{AppName},iniciar");
}
And I could use this same string later when required because it has been declared outside the method, for example here I needed to write AppName again:
private void DumpEventArgs(DocumentSavedEventArgs args_saved)
{
//StreamWriter file = new StreamWriter("C://Users//" + Environment.UserName + "//AppData//Roaming//Autodesk//" + Environment.UserName + ".txt", append: true);
//MessageBox.Show($"O utilizador {Environment.UserName} guardou um documento no {AppName} a {DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")}");
file.WriteLine($"{Environment.UserName},{DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")},{AppName},guardar");
}
Finally AppName retrieves what I wanted: "Autodesk Revit 2019".

Creating a new directory in c#

I would like to first create a new dir and then save a file into the following location C:\Users\Paul\Documents + \newfolder\nameOffile.xml.
Can this be achieved in C#. I currently have the following code but i cant seem to get it to work
XDocument doc = new XDocument(rootNode);
var dateAndTime = DateTime.Now;
var date = dateAndTime.Date.ToString("dd-MM-yyyy");
var patWithoutExtension = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);
string savedFilePah = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
var savedFile = savedFilePah + "/" + Directory.CreateDirectory("newFolder") + "/" + patWithoutExtension + "_" + date + ".xml";
//var savedFile = "C:/tmp/" + patWithoutExtension + "_" + date + ".xml";
doc.Save(savedFile);
lblFileUploaded.Text = "Success!";
it keeps failing on the doc.save with the following error
An unhandled exception of type 'System.IO.DirectoryNotFoundException'
occurred in System.Xml.dll
Additional information: Could not find a part of the path
'C:\Users\Paul\Documents\newFolder\test2_29-03-2015.xml'.
The problem seems to be with Directory.CreateDirectory("newFolder") which will create the folder under the working directory rather than under C:\Users\Paul\Documents.
Also, as a good practice I would advice to store the newly created folder in a dedicated folder. The advantages of this are twofold - you'll be able to watch this variable easily during debugging thus find out the exact location of the created folder and also, if an exception will be thrown you'll know the exact location of it.
Also, some Windows APIs might not accept a forward slash ('/') but will except a backslash ('\').
You must specify the full path to the directory you want to create, otherwise it's created at the working (running) folder:
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var myDir = Path.Combine(myDocs, "newFolder");
Directory.CreateDirectory(myDir);
var savedFile = Path.Combine(myDir, patWithoutExtension + "_" + date + ".xml");
This Directory.CreateDirectory("newFolder") is not creating the directory inside your Users folder: you're just passing it "newFolder", so it doesn't know that's where you want the folder. It will be creating it in your current working folder (e.g. bin/Debug).
Try passing the entire path to CreateDirectory:
string savedFilePath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
"newFolder");
Directory.CreateDirectory(savedFilePath);

c# open notepad and write in other computer [closed]

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 7 years ago.
Improve this question
I have project and I want to make a receipt of a buyer and write it on the notepad but my problem is when I install my application on other computer. the notepad is not opening and nothing happen when button click
var path = Path.Combine(Directory.GetCurrentDirectory(), "\\Receipt.txt");
using (StreamWriter w = new StreamWriter(path))
{
string x=label1.Text.Replace(" ",string.Empty);
string x2 = label2.Text.Replace(" ", string.Empty);
string x3 = label3.Text.Replace(" ", string.Empty);
string x4 = label4.Text.Replace(" ", string.Empty);
string x5 = label5.Text.Replace(" ", string.Empty);
w.Write("***************OFFICIAL RECEIPT*************** \r\n", true);
w.Write("\r\n"+"\r\n"+"***************Buyer Information*************"+"\r\n");
w.Write(x+"\r\n",true);
w.Write(x2+ "\r\n", true);
w.Write(x3 + "\r\n", true);
w.Write(x4 + "\r\n", true);
w.Write(x5+ "\r\n", true);
w.Write("\r\n" + "***************PURCHASE ITEM*****************" + "\r\n");
w.Write("ITEM QUANTITY PRICE" + "\r\n");
for (int xx = 0; xx<listBox1.Items.Count;xx++ )
{
w.Write(listBox1.Items[xx].ToString()+"\r\n");
}
w.Write("_____________________________________________"+ "\r\n");
w.Write("TOTAL " + totalprice+"\r\n"+"\r\n");
w.Write(" -THIS IS YOUR OFFICIAL RECEIPT- "+"\r\n");
w.Write(" THANK YOU FOR BUYING! ");
w.Close();
}
Process.Start("notepad.exe", path);
Try Changing
var path = Path.Combine(Directory.GetCurrentDirectory(), "\\Receipt.txt");
to
var path = Application.StartupPath + "\\Receipt.txt";
.
And also
Process.Start("notepad.exe", path);
to
Process.Start("notepad.exe", "\"" + path + "\"");
Changing this helped some people in some cases
providing quotes might help in case if the problem is because of empty spaces in folder names
Assuming this is winforms, as a test, change your catch block to look like this:
catch (Exception exception)
{
MessageBox.Show(exception.ToString());
throw;
}
If it's working on your dev box and not on another computer, I'd be willing to bet you have a permissions issue. Just try the code above and see what message you get. Then you can figure out what is wrong and how to fix it.

How to give path of a folder in server to save an image?

I'm trying to store an image into two applications (both published on server). This is my code to save the image :
string path = Server.MapPath("/Images/Landing/bottom_banner/");
string path1 = #"_http://10.241.193.22/Myapplication/Images/Landing/bottom_banner/";
HttpPostedFileBase photo = Request.Files["adup"];
if (photo.ContentLength != 0)
{
string lastPart = photo.FileName.Split('\\').Last();
Random random = new Random();
int rno = random.Next(0, 1000);
photo.SaveAs(path + rno + lastPart);
photo.SaveAs(path1 + rno + lastPart);
}
Note: Myapplication is another application hosted on the same server
My problem is I am able to save the image in my first application using Server.MapPath but when the compiler comes to the part photo.SaveAs(path1 + rno + lastPart) it gives an error:
The SaveAs method is configured to require a rooted path, and the path '_http://10.241.193.22/Myapplication/Images/Landing/bottom_banner/676Chrysanthemum.jpg' is not rooted
Please suggest how can I eliminate this issue?
I am not sure whether this is right but can you do this ?
In the current application store the Server.MapPath value and then replace the current application name with "Myapplication" and then add the trailing path. Something like this
string path1 = Server.MapPath("");
path1.Replace("Application1", "Myapplication"); //Considering "Application1" is the name of your current application
path1 += "/Images/Landing/bottom_banner/";
HttpPostedFileBase photo = Request.Files["adup"];
if (photo.ContentLength != 0)
{
string lastPart = photo.FileName.Split('\\').Last();
Random random = new Random();
int rno = random.Next(0, 1000);
photo.SaveAs(path1 + rno + lastPart);
}
There might be a permission problem with this one. I have not checked it. If it works please let me know.
You should POST image to the second server and use same method (Server.MapPath) there.
It's impossible to save image (or other file) at remote server.
if you know absolute paths (for example) 'C:\Web\ApplicationOne...\image.png\' and 'C:\Web\ApplicationTwo...\image.png' you can replace path difference like this:
photo.SaveAs(path + rno + lastPart);
photo.SaveAs(path.Replace("ApplicationOne", "ApplicationTwo") + rno + lastPart);

Java to C# code converter [duplicate]

This question already has answers here:
Tool to convert java to c# code [closed]
(4 answers)
Closed 6 years ago.
Are there any converters available that converts Java code to C#?
I need to convert the below code into C#
String token = new String("");
URL url1 =new URL( "http", domain, Integer.valueOf(portnum), "/Workplace/setCredentials?op=getUserToken&userId="+username+"&password="+password +"&verify=true");
URLConnection conn1=url1.openConnection();
((HttpURLConnection)conn1).setRequestMethod("POST");
InputStream contentFileUrlStream = conn1.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(contentFileUrlStream));
token=br.readLine();
String encodedAPIToken = URLEncoder.encode(token);
String doubleEncodedAPIToken ="ut=" + encodedAPIToken;//.substring(0, encodedAPIToken.length()-1);
//String doubleEncodedAPIToken ="ut=" + URLEncoder.encode(encodedAPIToken);
//String userToken = "ut=" + URLEncoder.encode(token, "UTF-8"); //URLEncoder.encode(token);
String vsId = "vsId=" + URLEncoder.encode(docId.substring(5, docId.length()), "UTF-8");
url="http://" + domain + ":" + portnum + "/Workplace/getContent?objectStoreName=RMROS&objectType=document&" + vsId + "&" +doubleEncodedAPIToken;
String vsId = "vsId=" + URLEncoder.encode(docId.substring(5, docId.length()), "UTF-8");
url="http://" + domain + ":" + portnum + "/Workplace/getContent?objectStoreName=RMROS&objectType=document&" + vsId + "&" +doubleEncodedAPIToken;
Thanks in advance
The below links might help:
Microsoft Launches Java-to-C# Converter;
Tangible Software Solutions inc..
The code is not very complicated, but if you don't have the time to translate it, you can use a tool like JLCA(Java Language Conversion Assistant 2.0).
You can try VaryCode Domain no longer exists and no valid snapshots in the Wayback Machine
But you used classes like URLEncoder, BufferedReader etc. that are hard to convert to C# without losing some Java-specific features. For this particular part of code it is insignificant but in prospect you can get some unpredicted behavior of the whole converted program.

Categories

Resources