Getting formatexception - c#

I am getting a Formatexception from the below code. I can't seem to fix it. What is wrong? Thanks
var res = dropDown.SelectedValue;
var zip = String.Format("{0}/FileBrowser/FOLDERNAME/filer/" + temp + ", projectPath");

Due to {0} in the format string
"{0}/FileBrowser/FOLDERNAME/filer/" + temp + ", projectPath"
String.Format expects an argument after it.
Did you mean something like
var zip = String.Format("{0}/FileBrowser/FOLDERNAME/filer/{1}", projectPath, temp);

Related

Find element in json file

I have JSON file like below, and I want to find a specific string or list of strings in this file.
I need to know if the values are in this file:
{
"naglowek": {
"dataGenerowaniaDanych": "20200107",
"liczbaTransformacji": "5000",
"schemat": "RRRRMMDDNNNNNNNNNNBBBBBBBBBBBBBBBBBBBBBBBBBB, gdzie R to cyfra roku, M – miesiąca, D - dnia daty generowania pliku, N to cyfra NIPu, a B to cyfra rachunku bankowego"
},
"skrotyPodatnikowCzynnych": [
"0000023d01e60fa522c2535d37c93051bdb9bc74e31b824460cd743a66a5282abb45567e43f09cfb26cd454b75ee6d6b0dfa83ef26db33581510afa421c3d430",
"0000025fe2175d2639990a7918baf727c41bbf554b1a88b679e32f3dc460c4dc44454b6a98417c31c4f2ee9e1c705ff951a1d7601553b327ec380213f2186a0f",
"00000cd37d8ded5c477552f61b647bcf9e6a967036823b7515b1e01e7fe3fe1854c470fb30f56beef1bc80d83d7350a53fe8677cb932f4f251837a767e0f8d63",
"00000d939549219dd4cd795c9b9680a3e5147791b1ddc4148f3463d6b3aa22849bcc30729cc60fc1282977d52d635c70d353f450c2abaef22f7d22439ac7b6e6",
"00001df757bb678d654308b1137c7dc8381d0457043009f4fc63edab93b32f60e1f460375e7da6965dbfd58f447d173c4c6c42add0d3dac181816782cf297cd8",
"0000248aef22c8ebddebd272cdc03e023f1dca221a5c7a731ade2989f1996b00b440c7410d52b89ef6f7927608bed66ad42a230f8e2cf86b97037597640d1da0",
"00002c000cd48dc44e63fa56d314962ff16b08c2e135a4c5352261a8e1c6b6fed9fefa01f01494d554e3158039450811a727c32576656d80963ed7b81a3732e3",
"00003666894d6872169f1f5212ba30a7441580f90d115823ca2d9cb6c5aca6e58ce277943bb284dd52cd669e8f05adba8d406ea8fb81c3e26bfce46b1cf8f120",
"00003bb55a8f67914ff5553a42f2bf2c8456b4f5d1a140ffdb1069442122114c61ad7bcbc715b35862c9e4566a8ddfbe9d9ca25457daa4cda51cdd796252b770",
"000041debf38337bb23391ccc9624483370a4e2d63dc4634c4f7c8d9071e5337d65464e59feedebe082bb7cbf6bb0a132b92194be457c92b1111132a51c81dcf",
"00004c88c01bc05ed4aa0df33cdbbe41aa77d49f94a6c9ee35efe6a59eca5cdea735acff28f05fb3d960973227b27ec81444b9afe14323fd2fc53a991b42c6ce"]
}
I need to find in this file specific string (one of the hashes)
I tried this:
public bool FindInFile(string sha512, string filePath, string date)
{
JObject o1 = JObject.Parse(File.ReadAllText(filePath + date + ".json"));
// read JSON directly from a file
using (StreamReader file = File.OpenText(filePath + date + ".json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject)JToken.ReadFrom(reader);
IEnumerable<JToken> pricyProducts = o2.SelectTokens("[?($.skrotyPodatnikowCzynnych == " + sha512 + ")]");
}
return true;
}
This should do the trick
public bool FindInFile(string sha512, string filePath, string date)
{
var obj = JObject.Parse(File.ReadAllText(filePath + date + ".json"));
return obj["skrotyPodatnikowCzynnych"].Children().Values<string>().Contains(sha512);
}
if you are sure the file is a valid json and do not contain other fields, why bother parsing it ? just look for the strings in it...
Otherwise just use linq to see if the query you wrote yields Any result...
pricyProducts.Any()
If it does not return any results ever, just fix the query (which i think is wrong)...
https://www.newtonsoft.com/json/help/html/SelectToken.htm
o2.SelectTokens("[?($.skrotyPodatnikowCzynnych == " + sha512 + ")]")
probably should be
o2.SelectTokens("$.skrotyPodatnikowCzynnych[?(# == '" + sha512 + "')]"

Could not find a part of the path in c#

I am trying to build a method which is able to write in a file the number of files in another folder. I already got it but it does not work because gives me an error:
Could not find a part of the path '
C:\Users\Administrator\Desktop...\bin\release\%USERPROFILE%\AppData\Local_logC'
This is my code:
private static int GetCountGFiles(string dirname)
{
int fileCount = 0;
dirname = dirname.TrimEnd(new char[] { '\\' }) + #"\";
var fixedDirname = Environment.ExpandEnvironmentVariables(dirname);
fileCount += System.IO.Directory.GetFiles(fixedDirname).Length;
string[] all_subdirs = System.IO.Directory.GetDirectories(dirname);
foreach (string dir in all_subdirs)
fileCount += GetCountGFiles(dirname);
string data = string.Format("LogReg.txt");
System.IO.Directory.CreateDirectory(filePath);
var fileandpath = filePath + data;
using (StreamWriter writer = File.AppendText(fileandpath))
{
writer.WriteLine("[" + DateTime.Now + "]" + " - " + "Nº de Records: (" + fileCount.ToString() + ")");
}
return fileCount;
}
And then I call the method like this :
GetCountGFiles(#"%USERPROFILE%\AppData\Local\Cargas - Amostras\_logsC\");
What should I do?
Methods like Directory.GetFiles and Directory.GetDirectories will not automatically figure out what the environment variables that you pass to it are. You need to do that manually with Environment.ExpandEnvironmentVariables. For example:
var fixedDirname = Environment.ExpandEnvironmentVariables(dirname);
Now you can do this:
fileCount += System.IO.Directory.GetFiles(fixedDirname).Length;
(PS No need to use ToString() on a string)
That "%USERPROFILE%" part is a placeholder for an environment variable. The file APIs have no idea how to handle that.
You need to use Environment.ExpandEnvironmentVariables on your input string,
before passing it to Directory.GetFiles

c# executed even when in false loop

I am trying to use a basic if else case, but the if is executed no matter what.
This is the code found in the backend, on the aspx.cs file.
if (1==2)
{
// 22/09/2014 12:00:00 AM for en
//format date for submit
Dateformatted = this.DateField.Value.ToString();
DateSplit = Dateformatted.Split('/');
yearAt0 = DateSplit[2].Split(' ');
Datetosubmit = yearAt0[0] + "/" + DateSplit[1] + "/" + DateSplit[0] + " 00:00:00";
}
else
{
// 2014-09-22 00:00:00 for fra
//format date for submit
Dateformatted = this.DateField.Value.ToString();
DateSplit = Dateformatted.Split('-');
dayAt0 = DateSplit[2].Split(' ');
Datetosubmit = DateSplit[0] + "/" + DateSplit[1] + "/" + dayAt0[0] + " 00:00:00";
}
This is the error I get (line 1209 is red):
System.IndexOutOfRangeException: Index was outside the bounds of the array.
Line 1207: string Dateformatted = this.DateFieldEdit.Value.ToString();
Line 1208: string[] DateSplit = Dateformatted.Split('/');
Line 1209: string[] yearAt0 = DateSplit[2].Split(' ');
Line 1210: string Datetosubmit = yearAt0[0] + "/" + DateSplit[1] + "/" + DateSplit[0] + " 00:00:00";
Line 1211:
This clearly indicates that the code inside the false part of the if statement was executed. Is there a reason for this? How can I fix this?
Note: The if (1==2) was added to simplify the example, it is normally a parameter
You can see this effect if your binaries and your PDB files are out of sync. If you are using the updated PDBs, but the old binaries, that would definitely explain this scenario.
The easiest way to fix this to to completely clean and rebuild everything. Deleting everything in your bin and obj folders for good measure. You should also restart the IIS instance you are using.

How to correctly us .replace function?

Trying to use a .replace function to take out the breaks (<br> and </br>) though having trouble with the code I have been given.
Here is what I am working with.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
var rawStream = sr.ReadToEnd();
sr.Close();
var myBuilder = new StringBuilder();
myBuilder.AppendLine("Employee Name : " + rawStream.Between("<span id=\"Label_DisplayFullName\">", "</span>"));
myBuilder.AppendLine("Title: " + rawStream.Between("<span id=\"Label_Title\">", "</span>"));
myBuilder.AppendLine("Location : " + rawStream.Between("<span id=\"Label_Location\">", "</span>"));
myBuilder.AppendLine("Department : " + rawStream.Between("<span id=\"Label_Department\">", "</span>"));
myBuilder.AppendLine("Group: " + rawStream.Between("<span id=\"Label_Group\">", "</span>"));
myBuilder.AppendLine("Office Phone : " + rawStream.Between("<span id=\"Label_IntPhoneNumber\">", "</span>"));
myBuilder.AppendLine("Mobile Phone : " + rawStream.Between("<span id=\"Label_BusMobile\">", "</span>"));
richTextBox1.Text = myBuilder.ToString();
Though I understand the function should be like so:
public string Replace( string oldValue, string newValue )
I just dont understand how this works in my code as I dont really have a "string" but I have a string builder.
Any assistance would be huge.
What does all your StringBuilder stuff have to do with removing the breaks? Your string is in the rawStream variable (quite badly named) (that's what ReadToEnd() gives you), so you'd just:
rawStream = rawStream.Replace("<br>", "");
rawStream = rawStream.Replace("<br />");
There are two things you could do:
On the one hand, you do assemble your string with a StringBuilder, however, you eventually convert the contents of that string builder into a string when you call myBuilder.ToString(). That is where you could invoke Replace:
richTextBox1.Text = myBuilder.ToString().Replace("<br>", "").Replace("</br>", "");
Alternatively, StringBuilder has a Replace method of its own, so you could invoke that before transforming the string builder contents into a string:
myBuilder.Replace("<br>", "");
myBuilder.Replace("</br>", "");
Note that the latter can alternatively be invoked in a chained fashion, as well, though that is arguably less readable:
richTextBox1.Text = myBuilder.Replace("<br>", "").Replace("</br>", "").ToString();
Since replace returns string you can chain them
rawStream = rawStream.Replace("<br>","").Replace("<br/>","").Replace("<br />","");
Can't you just put it after the ToString() call?
richTextBox1.Text = myBuilder.ToString().Replace("string1", "string2");
As mentioned in the comments you can also call it on the stringbuilder object itself.
richTextBox1.Text = myBuilder.Replace("string1", "string2").ToString();
Try this.
richTextBox1.Text = myBuilder.Replace("<br>", String.Empty).Replace("</br>", String.Empty).ToString();
Or
var rawStream = sr.ReadToEnd().Replace("<br>", String.Empty).Replace("</br>", String.Empty);

c# building strings domains

I am trying to download images. Their link may be image.png or http://www.example.com/image.png.
I made the image.png be added to the host and passed it to a list. So image.png is now http://www.example.com/image.png
But if the other type is used what I get is http://www.example.com//http://www.example.com/image.png
All I need is to get the string after the third slash. Here is some code I am tried to use:
try
{
path = this.txtOutput.Text + #"\" + str4 + etc;
client.DownloadFile(str, path);
}
catch(Exception e)
{
var uri = new Uri(str);
String host = (String) uri.Host;
String pathToFile = "http://" + host + "/";
int len = pathToFile.Length;
String fin = str.Substring(len, str.Length - len);
path = this.txtOutput.Text + #"\" + str4 + etc;
client.DownloadFile(fin, path);
}
What are these variables all about, like str4, etc and so on? Instead of the try catch you could check wheter the string is a valid uri. Give a look here. Try to debug you code line on line and check every single variable, then you will see which line makes the mistake.
EDIT
If I understodd you right, then this would be your solution:
string wrongResult = "example.com//http://www.example.com/image.png";
string shouldResult = "example.com/image.png";
int listIndexOfHttp = wrongResult.LastIndexOf("http:");
string correctResult = wrongResult.Substring(listIndexOfHttp);
When not please describe more specific from where you get this and it is always the same structure? or alaways different?

Categories