[英]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.