[英]Changing a Variable A-Z if file exists(C#)
大家好,我目前正在根據文件是否存在獲取下一個變量,但知道必須有一種更簡單的方法。 這個線程通過字母表迭代 - C#a-caz給了我一些很好的見解,但我遇到了一些問題用我所擁有的東西實現它。 任何建議都會非常感激。 謝謝
//Generate Motor Spacer Part Number
textBox3.Text = "MLB028A-MTRSPR-" + "z" + "-" + "y";
if (comboBox3.Text == "28mm (NEMA 11)") textBox3.Text = textBox3.Text.Replace("z", "B");
if (comboBox3.Text == "28mm (NEMA 11)") textBox3.Text = textBox3.Text.Replace("y", "A");
//Generate Motor Spacer Part Descriptions
textBox5.Text = "SPACER, " + comboBox3.Text + ", CFG-" + "y" + " MLB028";
if (comboBox3.Text == "28mm (NEMA 11)") textBox5.Text = textBox5.Text.Replace("y", "A");
string B = @"C:\Engineering\Engineering\SW Automation\Linear Actuator Technology\MLC Series\Models\MLB028Z-MTRSPR-B-A.SLDPRT";
if (File.Exists(B))
{
testBox3.Text = textBox3.Text.Replace("y", "B");
textBox5.Text = textBox5.Text.Replace("y", "B");
}
string C = @"C:\Engineering\Engineering\SW Automation\Linear Actuator Technology\MLC Series\Models\MLB028Z-MTRSPR-B-B.SLDPRT";
if (File.Exists(C))
{
testBox3.Text = textBox3.Text.Replace("y", "C");
textBox5.Text = textBox5.Text.Replace("y", "C");
}
看看這段代碼:
textBox3.Text.Replace("y", "B");
這不符合你的想法。
string.Replace
不會更改現有字符串的內容(它不能,字符串是不可變的)。 它返回一個替換的新字符串。 所以你可能想要:
textBox3.Text = textBox3.Text.Replace("y", "B");
可能還有其他問題-很難理解,因為代碼相當復雜-但那(以及其他類似的代碼)肯定是有問題的。
好吧,我不清楚你究竟想要完成什么。 如果您嘗試使用基於您在具有特定文件名的目錄中找到的第一個文件的值填充幾個文本框,請嘗試以下操作:
void PopulateTextBoxes()
{
string format = "MLB028A-MTRSPR-B-{1}";
string format2 = "SPACER, {0}, CFG-{1} MLB028";
string fileName = @"C:\Engineering\Engineering\SW Automation\Linear Actuator Technology\MLC Series\Models\MLB028Z-MTRSPR-B-{1}.SLDPRT";
for(string start = "A"; start != "Z"; start = GetNextBase26(start))
{
if(File.Exists(String.Format(fileName,start)))
{
textBox3.Text = String.Format(format,start);
textBox5.Text = String.Format(format2,textBox3.Text,start);
break;
}
}
}
// CODE FROM http://stackoverflow.com/questions/1011732/iterating-through-the-alphabet-c-sharp-a-caz
private static string GetNextBase26(string a)
{
return Base26Sequence().SkipWhile(x => x != a).Skip(1).First();
}
private static IEnumerable<string> Base26Sequence()
{
long i = 0L;
while (true)
yield return Base26Encode(i++);
}
private static char[] base26Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
private static string Base26Encode(Int64 value)
{
string returnValue = null;
do
{
returnValue = base26Chars[value % 26] + returnValue;
value /= 26;
} while (value-- != 0);
return returnValue;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.