通过系统IO获取文件名
我正在开发一个 C# 脚本,该脚本必须在运行时访问随机文件,问题是这些文件是由另一个源动态生成的,我无法知道它们的名称,我已经解决了第一个问题是获取我的工作目录中有多少个文件:
s = @"C:\Imagenes";
System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(s);
int files;
files = d.GetFiles().Length;
Debug.Log(files.ToString());
return files;
现在我想访问我的工作目录中的随机元素,但由于我不知道它们的名字是什么,有没有办法通过以下方式获取它们的名字索引什么的?
I'm working on a C# script that has to access a random file during runtime, the problem is that the files are being generated on the fly by another source and I have no means of knowing their names, I have solved a first issue which is to get how many files there are in my working directory:
s = @"C:\Imagenes";
System.IO.DirectoryInfo d = new System.IO.DirectoryInfo(s);
int files;
files = d.GetFiles().Length;
Debug.Log(files.ToString());
return files;
Now I would like to acces a random element in my working dicrectory, but since I don't have a clue what their names are, is there a way to get their names by index or something?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
DirectoryInfo.GetFiles 将为您提供 fileInfo 对象数组。从中您可以使用 FileInfo.Name 获取文件名
DirectoryInfo.GetFiles will give you array of fileInfo objects. From that you can get the file name using FileInfo.Name
您需要使用
d.GetFiles()
返回的FileInfo
对象:You need to use the
FileInfo
objects that are returned byd.GetFiles()
:尝试
查看
try
see
不知道为什么你想要一个随机文件,但这应该可行(除了在计算长度和获取随机文件期间文件被删除)
Not sure why you want a random file, but this should work (except files get deleted during calculation of length and getting a rondom one)