通过系统IO获取文件名

发布于 2024-11-30 14:09:41 字数 392 浏览 0 评论 0原文

我正在开发一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

萧瑟寒风 2024-12-07 14:09:41

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

沫离伤花 2024-12-07 14:09:41

您需要使用 d.GetFiles() 返回的 FileInfo 对象:

DirectoryInfo d = new DirectoryInfo("c:\\path");

foreach (FileInfo file in d.GetFiles())
{
    string name = file.Name;
}

You need to use the FileInfo objects that are returned by d.GetFiles():

DirectoryInfo d = new DirectoryInfo("c:\\path");

foreach (FileInfo file in d.GetFiles())
{
    string name = file.Name;
}
浪漫之都 2024-12-07 14:09:41

尝试

FileInfo[] fileinfos = d.GetFiles();

foreach (FileInfo FI in fileinfos)
{
string fullname = FI.FullName;
string name = FI.Name;

// do someting...
}

查看

try

FileInfo[] fileinfos = d.GetFiles();

foreach (FileInfo FI in fileinfos)
{
string fullname = FI.FullName;
string name = FI.Name;

// do someting...
}

see

唯憾梦倾城 2024-12-07 14:09:41

不知道为什么你想要一个随机文件,但这应该可行(除了在计算长度和获取随机文件期间文件被删除)

int length = d.GetFiles().Length;
Random rnd = new Random();
var randomFile = d.GetFiles().ElementAt(rnd.Next(0, length-1);

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)

int length = d.GetFiles().Length;
Random rnd = new Random();
var randomFile = d.GetFiles().ElementAt(rnd.Next(0, length-1);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文