C# 如何分配全局数组中的每个文件名?
我使用多个文件上传,我想用名为C# 如何分配全局数组中的每个文件名?,c#,asp.net,C#,Asp.net,我使用多个文件上传,我想用名为img的全局数组分配每个文件名,使用foreach在asp.net/c#中如何实现 为此,我将使用列表: List<string> img = new List<string>(); foreach (string s in Request.Files) { HttpPostedFile file = Request.Files[s]; int fileSizeInBytes = file.ContentLength;
img
的全局数组分配每个文件名,使用foreach在asp.net/c#中如何实现
为此,我将使用列表
:
List<string> img = new List<string>();
foreach (string s in Request.Files)
{
HttpPostedFile file = Request.Files[s];
int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
{
img.add(fileName);
fileExtension = Path.GetExtension(fileName);
file.SaveAs(filename);
}
List img=new List();
foreach(Request.Files中的字符串s)
{
HttpPostedFile file=Request.Files[s];
int fileSizeInBytes=file.ContentLength;
字符串文件名=file.fileName;
字符串fileExtension=“”;
如果(!string.IsNullOrEmpty(文件名))
{
添加(文件名);
fileExtension=Path.GetExtension(文件名);
file.SaveAs(文件名);
}
下面是一个很好的解释,解释了为什么在C#中使用列表
几乎总是比使用数组
更好:
如果您能更好地解释一下您要完成的任务,我可能会改进这个答案。谢谢,我有一个包含img1、img2、img3和img4的项目表。我想使用linq to sql将图像路径插入到这些列img1、img2等中,所以我决定在数组中分配每个路径,然后分配数组使用LINQINDEX您可以像在数组中一样在列表中按索引获取项。只需使用:int-myFirstImg=img[0];谢谢,但当int-myFirstImg=img[0];它会显示此错误系统。ArgumentOutOfRangeException这是因为您引用的索引不存在。只需检查它是否存在或img.Count>0即可(或者你需要的任何号码)。
List<string> img = new List<string>();
foreach (string s in Request.Files)
{
HttpPostedFile file = Request.Files[s];
int fileSizeInBytes = file.ContentLength;
string fileName = file.FileName;
string fileExtension = "";
if (!string.IsNullOrEmpty(fileName))
{
img.add(fileName);
fileExtension = Path.GetExtension(fileName);
file.SaveAs(filename);
}