rokkonet

PC・Androidソフトウェア・アプリの開発・使い方に関するメモ

java jcifs-ng SmbFileクラスのコンストラクタ引数のURLは末尾にスラッシュ(/)を付ける

2021 Aug. 14.
2021 Aug. 13.

SMBサーバーに接続するjcifs-ngライブラリでのSmbFileクラスのコンストラクタの引数とするURLは末尾にスラッシュ(/)を付ける。

出典
android - jcifs-ngのSmbFile#listFiles()で得られるファイルが実際と異なるもの(フルパスから直上の親ディレクトリが失われたもの)となる - スタック・オーバーフロー

SmbFile (jCIFS NG 2.0.3 API)

androidでの実装例

MainActivity.kt

    // 認証情報
    //////////////////////////////////////////////
    // Please replace these values to your data //
    val user = "USER"
    val password = "PASSWORD"
    val domain = "192.168.1.1"
    val smbroot = "smb://" + domain + "/MY/SMB/DIR/"
        // smbrootの末尾にはスラッシュ(/)を付ける
    //////////////////////////////////////////////

    val TAG: String = "MySMB"

    // coroutine準備
    private val job = Job()
    override val coroutineContext: CoroutineContext
        get() = Dispatchers.Main + job

    // 終了時のcoroutineのキャンセル設定
    override fun onDestroy() {
        job.cancel()
        super.onDestroy()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        launch {
            withContext(Dispatchers.IO) {
                val smb = connectSMB(user, password, domain, smbroot)
                Log.d(TAG, "Got SMB: " + smb.path)

                if (smb.isDirectory) {
                    for (eachFile in smb.listFiles()) {
                        Log.d(TAG, "CASE1 " + eachFile.path)
                    }
                } else {
                    Log.d(TAG, "CASE2 " + smb.path)
                }
            }
        }

    private suspend fun connectSMB(user: String, password: String, domain: String, smbroot: String): SmbFile {
        lateinit var smb: SmbFile
        coroutineScope {
            smb = async(Dispatchers.IO) {
                val prop = Properties()
                prop.setProperty("jcifs.smb.client.minVersion", "SMB202")
                prop.setProperty("jcifs.smb.client.maxVersion", "SMB300")
                val bc = BaseContext(PropertyConfiguration(prop))
                val creds = NtlmPasswordAuthentication(bc, domain, user, password)
                val auth: CIFSContext = bc.withCredentials(creds)
                SmbFile(smbroot, auth)
            }.await()
        }
        return smb
    }