webForumDet fria alternativet

Lista filer beroende på filändelse

.NET

1 svar · 361 visningar · startad av edebro

Medlem sedan aug. 2001261 inlägg
Frågan#1

Jag ska göra en webbsida som listar alla bildfiler från en mapp. Just nu testar jag bara lite med en vanlig desktop app. Så här ser min kod ut för tillfället;

using System;
using System.IO;

class Test 
{
	public static void Main() 
	{
		string _directory = @"c:\inetpub\work\ufk";
		try 
		{
			DirectoryInfo di = new DirectoryInfo(_directory);
			// Get only subdirectories that contain the letter "p."
			DirectoryInfo[] dirs = di.GetDirectories();
			FileInfo[] files = null;
			
			Console.WriteLine("Number of directories: {0}", dirs.Length);
			// Count all the files in each subdirectory that contain the letter "e."
			foreach (DirectoryInfo diNext in dirs) 
			{
				Console.WriteLine("{0}", diNext);
				
				files = diNext.GetFiles("*.aspx");
				foreach (FileInfo fiNext in files) {
					Console.WriteLine("    {0}", fiNext);
				}
			}
		} 
		
		catch (Exception e) 
		{
			Console.WriteLine("The process failed: {0}", e.ToString());
		}
	}
}

Som ni ser så letar den rätt på alla underkataloger i mappen c:\inetpub\work\ufk, och sedan plockar den fram alla .aspx-filer i undermapparna.
Det jag vill kunna göra är att specifiera flera filändelser, typ;

files = diNext.GetFiles("*.aspx;*.ascx");

Som sagt, det är bara en test så bry er inte om filändelserna osv.

Tacksam för svar!

Medlem sedan mars 20002 836 inlägg
#2

Helo!
satt för ett väldans tag sedan och ville ha samma funktionalitet ... tyvärr hittade jag inget i SDK'n (finns kanske) utan blev tvungen att skriva min egen "sökmaskin" för att lista filer med vissa filändelse(r)
Nu kodar jag VB och inte C# men hoppas att du kan "konvertera" min VB-kod till C#

I min .vb-fil som sedan ska kompileras:

Imports System
Imports System.Collections
Imports System.IO

    Public Class Files

        Public Filelist As New FileInfoCollection()

        Public Sub New(ByVal folderPath As String, ByVal extensions As String())
            LoadFiles(folderPath, extensions)
        End Sub

        Private Sub LoadFiles(ByVal path As String, ByVal extensions As String())
            Dim _dirs As String() = Directory.GetDirectories(path)
            Dim _dir As String

            For Each _dir In _dirs
                Dim _file As String
                Dim _ext As String

                '## -- loop through all the extensions --
                For Each _ext IN extensions
                    For Each _file IN Directory.GetFiles(_dir, _ext)
                        Dim _fi As New FileInfo()
                            _fi.Path = _file

                            Filelist.Add(_fi)
                    Next _file
                Next _ext

                '## -- get folders and files in _dir --
                LoadFiles(_dir, extensions)
            Next _dir
        End Sub

    End Class

    Public Class FileInfo
        Private _path As String
        Private _filename As String
        Private _extension As String

        Public Property Path() As String
            Get
                Dim _index As Integer = _path.LastIndexOf("\")
                Return _path.Substring(0,_index)
            End Get
            Set(ByVal Value As String)
                _path = Value

                Try
                    Dim _filenames As String() = _path.Split("\")
                        _filename = _filenames(_filenames.Length - 1)

                    Dim _index As Integer = _path.LastIndexOf(".")
                        _extension = _path.Substring(_index)
                Catch

                End Try
            End Set
        End Property

        Public ReadOnly Property Filename() As String
            Get
                Return _filename
            End Get
        End Property

        Public ReadOnly Property Extension() As String
            Get
                Return _extension
            End Get
        End Property

        Public Sub New()
        End Sub
    End Class

    Public Class FileInfoCollection
        Inherits CollectionBase

        Public Default Property Item(Index As Integer) As FileInfo
            Get
                Return CType(Me.List.Item(Index), FileInfo)
            End Get
            Set(ByVal Value As FileInfo)
                Me.List.Item(Index) = Value
            End Set
        End Property

        Public Function Add(Value As FileInfo) As Integer
            Return CType(Me.List.Add(Value), Object)
        End Function
    End Class

Det enda som sedan behövs för att lista alla filer med de valda extensions är:

    Public Sub Page_Load(Sender As Object, E As EventArgs)
        Dim _extensions As String() = {"*.htm","*.aspx","*.ascx"}

        Dim _allFiles As New Files(Server.MapPath("\"), _extensions)

        dgFiles.DataSource = _allFiles.Filelist
        dgFiles.DataBind()
    End Sub

Det dumma är att *.htm även tar .html ... likadant med *.asp tar *.aspx oxå ....

cya,
/PatrikB

257 ms totalt · 4 externa anrop · v20260731065814-full.a51de22e
127 ms — deklarationer (db)
0 ms — hämta statistik (cache)
127 ms — hämta tråd, inlägg och bilagor (db)
121 ms — ändringar (db)