File Up/Down Load 드라이브 사용(?)

안녕하세요 ! 무더운 여름 장마 날씨에 고생하십니다…!
질문은 하기와 같습니다.

최대 10MB(?) 정도의 DB파일 하나를 드라이브에 올려두고, WPF 윈도우 어플리케이션 에서 Upload/Download를 구현해보려 하고 있습니다.

Network드라이브에 관해 찾아보고 하니 내부 로컬만 가능한것 같더라구요, 이에 관해서 사용 경험상 ** :innocent:무료**이며 적은 용량이기 때문에 사용에 용이한(?)것을 추천 부탁드립니다.
추가로 Synology 모델을 개인적으로 가지고 있는데, Sylongoy를 통해서 Up/Dn 경험이 있으신분이 있다면, 참조 예제를 통해 해보고있는데 생각보다 예외가 많이 발생하더라구요, 간편히 접근법(?)을 배울수 있으면 좋겠습니다 !

1개의 좋아요

여기서 드라이브란 특정 PC의 드라이브를 의미하나요? 구글 드라이브 같이 클라우드 스토리지를 의미하나요?
→ Synology 모델을 말씀하시는것으로 보아 PC의 드라이브를 의미하는 것인가요?

가장 쉽고 빠르게 구현하시려면 웹서버를 통해 파일 업/다운로드만 구현한 후 사용하시는 방법입니다.

제가 Synology 모델을 가지고 있지는 않지만 어떻게 안되는지 관련 코드를 공유해주시면 다른 분이 도움 드리기 편할 것 같네요.

1개의 좋아요
public static class NetDrive
    {

        /// <summary>
        /// Connects to the remote share
        /// </summary>
        /// <returns>Null if successful, otherwise error message.</returns>
        public static string ConnectToShare( string uri, string username, string password )
        {
            //Create netresource and point it at the share
            NETRESOURCE nr = new NETRESOURCE();
            nr.dwType = RESOURCETYPE_DISK;
            nr.lpRemoteName = uri;

            //Create the share
            int ret = WNetUseConnection( IntPtr.Zero, nr, password, username, 0, null, null, null );

            //Check for errors
            if (ret == NO_ERROR)
                return null;
            else
                return GetError( ret );
        }

        /// <summary>
        /// Remove the share from cache.
        /// </summary>
        /// <returns>Null if successful, otherwise error message.</returns>
        public static string DisconnectFromShare( string uri, bool force )
        {
            //remove the share
            int ret = WNetCancelConnection( uri, force );

            //Check for errors
            if (ret == NO_ERROR)
                return null;
            else
                return GetError( ret );
        }

        #region P/Invoke Stuff
        [DllImport( "Mpr.dll" )]
        private static extern int WNetUseConnection(
            IntPtr hwndOwner,
            NETRESOURCE lpNetResource,
            string lpPassword,
            string lpUserID,
            int dwFlags,
            string lpAccessName,
            string lpBufferSize,
            string lpResult
            );

        [DllImport( "Mpr.dll" )]
        private static extern int WNetCancelConnection(
            string lpName,
            bool fForce
            );

        [StructLayout( LayoutKind.Sequential )]
        private class NETRESOURCE
        {
            public int dwScope = 0;
            public int dwType = 0;
            public int dwDisplayType = 0;
            public int dwUsage = 0;
            public string lpLocalName = "";
            public string lpRemoteName = "";
            public string lpComment = "";
            public string lpProvider = "";
        }

        #region Consts
        const int RESOURCETYPE_DISK = 0x00000001;
        const int CONNECT_UPDATE_PROFILE = 0x00000001;
        #endregion

        #region Errors
        const int NO_ERROR = 0;

        const int ERROR_ACCESS_DENIED = 5;
        const int ERROR_ALREADY_ASSIGNED = 85;
        const int ERROR_BAD_DEVICE = 1200;
        const int ERROR_BAD_NET_NAME = 67;
        const int ERROR_BAD_PROVIDER = 1204;
        const int ERROR_CANCELLED = 1223;
        const int ERROR_EXTENDED_ERROR = 1208;
        const int ERROR_INVALID_ADDRESS = 487;
        const int ERROR_INVALID_PARAMETER = 87;
        const int ERROR_INVALID_PASSWORD = 1216;
        const int ERROR_MORE_DATA = 234;
        const int ERROR_NO_MORE_ITEMS = 259;
        const int ERROR_NO_NET_OR_BAD_PATH = 1203;
        const int ERROR_NO_NETWORK = 1222;
        const int ERROR_SESSION_CREDENTIAL_CONFLICT = 1219;

        const int ERROR_BAD_PROFILE = 1206;
        const int ERROR_CANNOT_OPEN_PROFILE = 1205;
        const int ERROR_DEVICE_IN_USE = 2404;
        const int ERROR_NOT_CONNECTED = 2250;
        const int ERROR_OPEN_FILES = 2401;

        private struct ErrorClass
        {
            public int num;
            public string message;
            public ErrorClass( int num, string message )
            {
                this.num = num;
                this.message = message;
            }
        }

        private static ErrorClass[] ERROR_LIST = new ErrorClass[] {
        new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"),
        new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"),
        new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"),
        new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"),
        new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"),
        new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"),
        new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"),
        new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"),
        new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"),
        new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"),
        new ErrorClass(ERROR_MORE_DATA, "Error: More Data"),
        new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"),
        new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"),
        new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"),
        new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"),
        new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"),
        new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"),
        new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"),
        new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"),
        new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"),
        new ErrorClass(ERROR_SESSION_CREDENTIAL_CONFLICT, "Error: Credential Conflict"),
    };

        private static string GetError( int errNum )
        {
            foreach (ErrorClass er in ERROR_LIST)
            {
                if (er.num == errNum) return er.message;
            }
            return "Error: Unknown, " + errNum;
        }
        #endregion

        #endregion
    }```

위 클래스를 이용해서
NetDrive.ConnectToShare( "NetworkDrive-Address", "id", "pwd");
실행 후 
if(!Directory.Exists("NetworkDrive-Address"), true);
   Directory.CreateDirectory("NetworkDrive-Address" + createfolderName);
System.IO.File.Copy(path, target);

![aa12|545x203](upload://iZPmp8LCMMbtQBmEYqjx3MnRSZB.jpeg)


저의 나스의 공유폴더 NetWorkDrive 경로를 입력했는데도 경로형식은 지원되지 않는다고 하네요..
Window상에서의 네트워크드라이브 추가 후 연결하면 정상 동작합니다
URL ex:) "https://mynas.synology.me:5006/MyWork"

원하는 방향 컨셉으로는 인터넷상의 (synology...등등)의 서버에 DB File을 올려두고 UpLoad/DownLoad 하는 기능이 필요로 해서 였습니다.
프로그램 실행은 각개의 PC에서 인터넷사용이 가능만 하면 UpLoad/DownLoad 기능을 쓰려구요
1개의 좋아요

찾아보니 https면 webdav 프로토콜로 접근해야 되는 것 같아요.
연관된 패키지 공유 드리니 추가해서 테스트 해 보시는게 어떨까요?
사용법도 잘 나와있네요.

Github

사용법

Install-Package WebDav.Client
var clientParams = new WebDavClientParams
{
    BaseAddress = new Uri("http://mywebdav/"),
    Credentials = new NetworkCredential("user", "12345")
};
using (var client = new WebDavClient(clientParams))
{
    await client.Mkcol("mydir"); // create a directory

    await client.Copy("source.txt", "dest.txt"); // copy a file

    await client.Move("source.txt", "dest.txt"); // move a file

    await client.Delete("file.txt", "dest.txt"); // delete a file

    using (var response = await client.GetRawFile("file.txt")) // get a file without processing from the server
    {
        // use response.Stream
    }

    using (var response = await client.GetProcessedFile("file.txt")) // get a file that can be processed by the server
    {
        // use response.Stream
    }

    await client.PutFile("file.xml", File.OpenRead("file.xml")); // upload a resource
}

참고

3개의 좋아요

도움 주셔서 감사합니다.

테스트 진행 결과
clientParams 객체 생성 → 데이터 null

var client = new WebDavClient(clientParams)) → 데이터 null

경로 url 변경 시도 하여 진행해 보았지만 계속 비어있는 상태네요…(?)

크롬상에서는 같은경로도 폴더 화면이 따로 나오는데 참 어렵네요,

1개의 좋아요

환경적인 요소일 것 같기는 한데, 의심되는 부분은 일전에 공유해주신 URL로 볼때 공인된 인증서를 사용하지 않으실 것 같아 https 인증서 검증을 무시하도록 처리가 필요할 것 같습니다.
그것 말고는 짚이는 곳이 딱히 없네요.

인증서 검증 무시는 아래 코드를 적용하시면 됩니다.

var httpClientHandler = new HttpClientHandler();
httpClientHandler.ServerCertificateCustomValidationCallback = ( message, cert, chain, sslPolicyErrors ) =>
{
    return true;
};
httpClientHandler.Credentials = new NetworkCredential( "user", "password" );
HttpClient httpClient = new HttpClient( httpClientHandler ) { BaseAddress = new Uri( server ) };
WebDavClient client = new WebDavClient( httpClient );

참고

2개의 좋아요