簡體   English   中英

如何使用路徑和名稱分隔文件路徑

[英]How to split a file path with path and name seperated

例如,我們如何分割文件路徑

String path=file:\C:\Users\id\work\target\test-classes\ean\sample.txt
to
String filePath=file:\C:\Users\id\work\target\test-classes\ean\
String filename=sample.txt

需要使用的功能

Paths.get(filePath,filename)

您可以使用file.getParent()獲取目錄路徑。

然后使用file.getName()獲取文件名。

如果從文件(使用System.IO添加)創建FileInfo對象,則可以將FullName屬性與Replace()一起使用以獲取路徑,並為名稱使用Name屬性。

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.IO;

namespace Generic_Unit_Tests
{
    [TestClass]
    public class FileAndPathTest
    {
        [TestMethod]
        public void GetFileNameAndPathTest()
        {
            string fullFileName = @"C:\Users\joey\Documents\Visual Studio 2012\Projects\Repo Docs and Notes\TestFile.txt";
            string filePath = string.Empty;
            string fileName = string.Empty;
            FileInfo fi = new FileInfo(fullFileName);
            filePath = fi.FullName.Replace(fi.Name, string.Empty);
            fileName = fi.Name;
            Console.WriteLine(string.Format("Path: {0}", filePath));
            Console.WriteLine(string.Format("File Name: {0}", fileName));
        }
    }
}

結果:

測試名稱:GetFileNameAndPathTest測試結果:通過的結果StandardOutput:
路徑:C:\\ Users \\ joey \\ Documents \\ Visual Studio 2012 \\ Projects \\ Repo Docs and Notes \\文件名:TestFile.txt

而鮑勃是你的叔叔。

喬伊

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM