我有以下C#代码(关于将文件上传到服务器)
for (int i = 0; i < Request.Files.Count-1; i++)
{
if (Request.ContentLength != 0)
{
int Size = Request.Files[i].ContentLength / 1024;
if (Size <= 512)
{
string LocalFile = Request.Files[i].FileName;
int dot = LocalFile.LastIndexOf('.');
string FileType = LocalFile.Substring(dot + 1);
if (FileType == "gif" || FileType == "jpg" || FileType == "png" || FileType == "GIF" || FileType == "JPG" || FileType == "PNG")
{
int LastIndex = LocalFile.LastIndexOf(@"\") + 1;
string File = LocalFile.Substring(LastIndex, LocalFile.Length - LastIndex);
string Path = Server.MapPath(" ../images/tracks") + "..\\" + File;
Request.Files[i].SaveAs(Path);
if (i != Request.Files.Count - 1)
ImageList += string.Format("images/tracks/{0}|", File);
else { ImageList += string.Format("images/tracks/{0}", File); }
}
}
else
{
Response.Write("The file is too big !");
}
}
else
{
Response.Write("Unknown Error !");
}
}
问题是有多个文件上传字段。
我想创建条件,检查文件后是否有文件[i](chack if file [i + 1]为空)
如果是,程序将执行以下代码:ImageList += string.Format("images/tracks/{0}", File);
其他:ImageList += string.Format("images/tracks/{0}|", File);
我的问题是病情应该如何?
Whish求救,谢谢!
答案 0 :(得分:1)
只需删除条件(如果)并添加具有结束字符的所有字符串。在循环结束时,如果是“|”,则可以删除最后一个字符。
在你的代码上:
for (int i = 0; i < Request.Files.Count-1; i++)
{
if (Request.ContentLength != 0)
{
int Size = Request.Files[i].ContentLength / 1024;
if (Size <= 512)
{
string LocalFile = Request.Files[i].FileName;
int dot = LocalFile.LastIndexOf('.');
string FileType = LocalFile.Substring(dot + 1);
if (FileType == "gif" || FileType == "jpg" || FileType == "png" || FileType == "GIF" || FileType == "JPG" || FileType == "PNG")
{
int LastIndex = LocalFile.LastIndexOf(@"\") + 1;
string File = LocalFile.Substring(LastIndex, LocalFile.Length - LastIndex);
string Path = Server.MapPath(" ../images/tracks") + "..\\" + File;
Request.Files[i].SaveAs(Path);
//if (i != Request.Files.Count - 1)
ImageList += string.Format("images/tracks/{0}|", File);
//else { ImageList += string.Format("images/tracks/{0}", File); }
}
}
else
{
Response.Write("The file is too big !");
}
}
else
{
Response.Write("Unknown Error !");
}
}
//Remove the last character
if (ImageList.EndsWith("|")) ImageList = ImageList.Remove(ImageList.Length - 1, 1);
}