Reputation: 5870
My goal is to implement an endpoint which gives back a nested list of all files and directories starting from a certain root directory, e.g. C:\Temp
. I have written the following code:
namespace API.Controllers
{
public class UploadController : BaseController
{
[Route("api/Uploaded", Order = -1)]
[ResponseType(typeof(IEnumerable<string[]>))] // <- this has to be adjusted, I guess.
public IHttpActionResult AutoUpload()
{
string[] entries = Directory.GetFileSystemEntries("C:\Temp", "*", SearchOption.AllDirectories);
// <-- Here should come some conversion to a nested JSON.
return Ok(entries);
}
}
}
When I am querying the endpoint, e.g. with curl -X POST --header 'Accept: application/json' 'http://localhost:63291/api/Uploaded'
the response is something
[
"C:\\\\Temp\\file1",
"C:\\\\Temp\\dir1\\file2",
"C:\\\\Temp\\dir1\\file3"
]
What I would rather like to have is something like the following
[
{ "~":
[ "file1" ]
},
{
"~/dir1":
[
"file2" ,
"file3"
]
}
]
I am sure it cannot be so complicated to convert my list into a nested JSON, but I somehow do not manage to do it. I fear, I am missing the appropriate search terms. Please help!
Upvotes: 0
Views: 345
Reputation: 90
First of all Attribute [ResponseType]
does not affect your response, it's just metadata that is used by for example swagger to document your endpoints.
Directory.GetFileSystemEntries
as Greg said returns collection (array) od strings representing paths. You need to parse your results to format you want i see that is something like File
class and Directory
containing File
but better approach it would be to use build in types like FileInfo
.
DirectoryInfo
class provides some useful methods that you could use:
Get all files in directory: https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.getfiles?view=netframework-4.8
Get all directories in directory: https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.getdirectories?view=netframework-4.8
Or also get both: https://learn.microsoft.com/en-us/dotnet/api/system.io.directoryinfo.getfilesysteminfos?view=netframework-4.8
Read about data types returned by that methods and use the best of it ;)
I think you will need to do some recursion to go through all subdirectories.
Upvotes: 2