SftpTests.cs 233 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546
  1. using System.Diagnostics;
  2. using Renci.SshNet.Common;
  3. using Renci.SshNet.IntegrationTests.Common;
  4. using Renci.SshNet.Sftp;
  5. namespace Renci.SshNet.IntegrationTests
  6. {
  7. // TODO: DeleteDirectory (fail + success
  8. // TODO: DeleteFile (fail + success
  9. // TODO: Delete (fail + success
  10. [TestClass]
  11. public class SftpTests : TestBase
  12. {
  13. private IConnectionInfoFactory _connectionInfoFactory;
  14. private IConnectionInfoFactory _adminConnectionInfoFactory;
  15. private IRemotePathTransformation _remotePathTransformation;
  16. [TestInitialize]
  17. public void SetUp()
  18. {
  19. _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
  20. _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
  21. _remotePathTransformation = RemotePathTransformation.ShellQuote;
  22. }
  23. [DataTestMethod]
  24. [DynamicData(nameof(GetSftpUploadFileFileStreamData), DynamicDataSourceType.Method)]
  25. public void Sftp_UploadFile_FileStream(int size)
  26. {
  27. var file = CreateTempFile(size);
  28. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  29. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  30. {
  31. client.Connect();
  32. var remoteFile = GenerateUniqueRemoteFileName();
  33. if (client.Exists(remoteFile))
  34. {
  35. client.Delete(remoteFile);
  36. }
  37. try
  38. {
  39. client.UploadFile(fs, remoteFile);
  40. using (var memoryStream = new MemoryStream(size))
  41. {
  42. client.DownloadFile(remoteFile, memoryStream);
  43. memoryStream.Position = 0;
  44. Assert.AreEqual(CreateFileHash(file), CreateHash(memoryStream));
  45. }
  46. }
  47. finally
  48. {
  49. if (client.Exists(remoteFile))
  50. {
  51. client.Delete(remoteFile);
  52. }
  53. }
  54. }
  55. }
  56. [TestMethod]
  57. public void Sftp_ConnectDisconnect_Serial()
  58. {
  59. const int iterations = 100;
  60. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  61. {
  62. for (var i = 1; i <= iterations; i++)
  63. {
  64. client.Connect();
  65. client.Disconnect();
  66. }
  67. }
  68. }
  69. [TestMethod]
  70. public void Sftp_ConnectDisconnect_Parallel()
  71. {
  72. const int iterations = 10;
  73. const int threads = 5;
  74. var startEvent = new ManualResetEvent(false);
  75. var tasks = Enumerable.Range(1, threads).Select(i =>
  76. {
  77. return Task.Factory.StartNew(() =>
  78. {
  79. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  80. {
  81. startEvent.WaitOne();
  82. for (var j = 0; j < iterations; j++)
  83. {
  84. client.Connect();
  85. client.Disconnect();
  86. }
  87. }
  88. });
  89. }).ToArray();
  90. startEvent.Set();
  91. Task.WaitAll(tasks);
  92. }
  93. [TestMethod]
  94. public void Sftp_BeginUploadFile()
  95. {
  96. const string content = "SftpBeginUploadFile";
  97. var expectedByteCount = (ulong)Encoding.ASCII.GetByteCount(content);
  98. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  99. {
  100. client.Connect();
  101. var remoteFile = GenerateUniqueRemoteFileName();
  102. if (client.Exists(remoteFile))
  103. {
  104. client.Delete(remoteFile);
  105. }
  106. try
  107. {
  108. using (var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(content)))
  109. {
  110. IAsyncResult asyncResultCallback = null;
  111. using var callbackCalled = new ManualResetEventSlim(false);
  112. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, ar =>
  113. {
  114. asyncResultCallback = ar;
  115. callbackCalled.Set();
  116. });
  117. Assert.IsTrue(asyncResult.AsyncWaitHandle.WaitOne(10000));
  118. // check async result
  119. var sftpUploadAsyncResult = asyncResult as SftpUploadAsyncResult;
  120. Assert.IsNotNull(sftpUploadAsyncResult);
  121. Assert.IsFalse(sftpUploadAsyncResult.IsUploadCanceled);
  122. Assert.IsTrue(sftpUploadAsyncResult.IsCompleted);
  123. Assert.IsFalse(sftpUploadAsyncResult.CompletedSynchronously);
  124. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResult.UploadedBytes);
  125. Assert.IsTrue(callbackCalled.Wait(10000));
  126. // check async result callback
  127. var sftpUploadAsyncResultCallback = asyncResultCallback as SftpUploadAsyncResult;
  128. Assert.IsNotNull(sftpUploadAsyncResultCallback);
  129. Assert.IsFalse(sftpUploadAsyncResultCallback.IsUploadCanceled);
  130. Assert.IsTrue(sftpUploadAsyncResultCallback.IsCompleted);
  131. Assert.IsFalse(sftpUploadAsyncResultCallback.CompletedSynchronously);
  132. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResultCallback.UploadedBytes);
  133. }
  134. // check uploaded file
  135. using (var memoryStream = new MemoryStream())
  136. {
  137. client.DownloadFile(remoteFile, memoryStream);
  138. memoryStream.Position = 0;
  139. var remoteContent = Encoding.ASCII.GetString(memoryStream.ToArray());
  140. Assert.AreEqual(content, remoteContent);
  141. }
  142. }
  143. finally
  144. {
  145. if (client.Exists(remoteFile))
  146. {
  147. client.Delete(remoteFile);
  148. }
  149. }
  150. }
  151. }
  152. [TestMethod]
  153. public void Sftp_Create_ExistingFile()
  154. {
  155. var encoding = Encoding.UTF8;
  156. var initialContent = "Gert & Ann & Lisa";
  157. var newContent1 = "Sofie";
  158. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  159. var newContent2 = "Lisa & Sofie";
  160. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  161. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  162. {
  163. client.Connect();
  164. var remoteFile = GenerateUniqueRemoteFileName();
  165. if (client.Exists(remoteFile))
  166. {
  167. client.DeleteFile(remoteFile);
  168. }
  169. try
  170. {
  171. client.WriteAllText(remoteFile, initialContent);
  172. #region Write less bytes than the current content, overwriting part of that content
  173. using (var fs = client.Create(remoteFile))
  174. using (var sw = new StreamWriter(fs, encoding))
  175. {
  176. sw.Write(newContent1);
  177. }
  178. var actualContent1 = client.ReadAllBytes(remoteFile);
  179. Assert.IsTrue(newContent1Bytes.IsEqualTo(actualContent1));
  180. #endregion Write less bytes than the current content, overwriting part of that content
  181. #region Write more bytes than the current content, overwriting and appending to that content
  182. using (var fs = client.Create(remoteFile))
  183. using (var sw = new StreamWriter(fs, encoding))
  184. {
  185. sw.Write(newContent2);
  186. }
  187. var actualContent2 = client.ReadAllBytes(remoteFile);
  188. Assert.IsTrue(newContent2Bytes.IsEqualTo(actualContent2));
  189. #endregion Write more bytes than the current content, overwriting and appending to that content
  190. }
  191. finally
  192. {
  193. if (client.Exists(remoteFile))
  194. {
  195. client.DeleteFile(remoteFile);
  196. }
  197. }
  198. }
  199. }
  200. [TestMethod]
  201. public void Sftp_Create_DirectoryDoesNotExist()
  202. {
  203. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  204. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  205. {
  206. client.Connect();
  207. if (client.Exists(remoteFile))
  208. {
  209. client.DeleteFile(remoteFile);
  210. }
  211. SftpFileStream fs = null;
  212. try
  213. {
  214. fs = client.Create(remoteFile);
  215. Assert.Fail();
  216. }
  217. catch (SftpPathNotFoundException ex)
  218. {
  219. Assert.IsNull(ex.InnerException);
  220. Assert.AreEqual("No such file", ex.Message);
  221. }
  222. finally
  223. {
  224. fs?.Dispose();
  225. if (client.Exists(remoteFile))
  226. {
  227. client.DeleteFile(remoteFile);
  228. }
  229. }
  230. }
  231. }
  232. [TestMethod]
  233. public void Sftp_Create_FileDoesNotExist()
  234. {
  235. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  236. {
  237. client.BufferSize = 512 * 1024;
  238. client.Connect();
  239. var remoteFile = GenerateUniqueRemoteFileName();
  240. if (client.Exists(remoteFile))
  241. {
  242. client.DeleteFile(remoteFile);
  243. }
  244. try
  245. {
  246. using (var imageStream = GetData("resources.issue #70.png"))
  247. {
  248. using (var fs = client.Create(remoteFile))
  249. {
  250. byte[] buffer = new byte[Math.Min(client.BufferSize, imageStream.Length)];
  251. int bytesRead;
  252. while ((bytesRead = imageStream.Read(buffer, offset: 0, buffer.Length)) > 0)
  253. {
  254. fs.Write(buffer, offset: 0, bytesRead);
  255. }
  256. }
  257. using (var memoryStream = new MemoryStream())
  258. {
  259. client.DownloadFile(remoteFile, memoryStream);
  260. memoryStream.Position = 0;
  261. imageStream.Position = 0;
  262. Assert.AreEqual(CreateHash(imageStream), CreateHash(memoryStream));
  263. }
  264. }
  265. }
  266. finally
  267. {
  268. if (client.Exists(remoteFile))
  269. {
  270. client.DeleteFile(remoteFile);
  271. }
  272. }
  273. }
  274. }
  275. [TestMethod]
  276. public void Sftp_AppendAllLines_NoEncoding_ExistingFile()
  277. {
  278. var initialContent = "\u0100ert & Ann";
  279. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  280. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  281. Environment.NewLine;
  282. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  283. {
  284. client.Connect();
  285. var remoteFile = GenerateUniqueRemoteFileName();
  286. if (client.Exists(remoteFile))
  287. {
  288. client.DeleteFile(remoteFile);
  289. }
  290. try
  291. {
  292. client.WriteAllText(remoteFile, initialContent);
  293. client.AppendAllLines(remoteFile, linesToAppend);
  294. var text = client.ReadAllText(remoteFile);
  295. Assert.AreEqual(expectedContent, text);
  296. // ensure we didn't write an UTF-8 BOM
  297. using (var fs = client.OpenRead(remoteFile))
  298. {
  299. var firstByte = fs.ReadByte();
  300. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  301. }
  302. }
  303. finally
  304. {
  305. if (client.Exists(remoteFile))
  306. {
  307. client.DeleteFile(remoteFile);
  308. }
  309. }
  310. }
  311. }
  312. [TestMethod]
  313. public void Sftp_AppendAllLines_NoEncoding_DirectoryDoesNotExist()
  314. {
  315. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  316. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  317. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  318. {
  319. client.Connect();
  320. if (client.Exists(remoteFile))
  321. {
  322. client.DeleteFile(remoteFile);
  323. }
  324. try
  325. {
  326. client.AppendAllLines(remoteFile, linesToAppend);
  327. Assert.Fail();
  328. }
  329. catch (SftpPathNotFoundException ex)
  330. {
  331. Assert.IsNull(ex.InnerException);
  332. Assert.AreEqual("No such file", ex.Message);
  333. }
  334. finally
  335. {
  336. if (client.Exists(remoteFile))
  337. {
  338. client.DeleteFile(remoteFile);
  339. }
  340. }
  341. }
  342. }
  343. [TestMethod]
  344. public void Sftp_AppendAllLines_NoEncoding_FileDoesNotExist()
  345. {
  346. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  347. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  348. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  349. {
  350. client.Connect();
  351. var remoteFile = GenerateUniqueRemoteFileName();
  352. if (client.Exists(remoteFile))
  353. {
  354. client.DeleteFile(remoteFile);
  355. }
  356. try
  357. {
  358. client.AppendAllLines(remoteFile, linesToAppend);
  359. var text = client.ReadAllText(remoteFile);
  360. Assert.AreEqual(expectedContent, text);
  361. // ensure we didn't write an UTF-8 BOM
  362. using (var fs = client.OpenRead(remoteFile))
  363. {
  364. var firstByte = fs.ReadByte();
  365. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  366. }
  367. }
  368. finally
  369. {
  370. if (client.Exists(remoteFile))
  371. {
  372. client.DeleteFile(remoteFile);
  373. }
  374. }
  375. }
  376. }
  377. [TestMethod]
  378. public void Sftp_AppendAllText_NoEncoding_ExistingFile()
  379. {
  380. var initialContent = "\u0100ert & Ann";
  381. var contentToAppend = "Forever&\u0116ver";
  382. var expectedContent = initialContent + contentToAppend;
  383. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  384. {
  385. client.Connect();
  386. var remoteFile = GenerateUniqueRemoteFileName();
  387. if (client.Exists(remoteFile))
  388. {
  389. client.DeleteFile(remoteFile);
  390. }
  391. try
  392. {
  393. client.WriteAllText(remoteFile, initialContent);
  394. client.AppendAllText(remoteFile, contentToAppend);
  395. var text = client.ReadAllText(remoteFile);
  396. Assert.AreEqual(expectedContent, text);
  397. // ensure we didn't write an UTF-8 BOM
  398. using (var fs = client.OpenRead(remoteFile))
  399. {
  400. var firstByte = fs.ReadByte();
  401. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  402. }
  403. }
  404. finally
  405. {
  406. if (client.Exists(remoteFile))
  407. {
  408. client.DeleteFile(remoteFile);
  409. }
  410. }
  411. }
  412. }
  413. [TestMethod]
  414. public void Sftp_AppendAllText_NoEncoding_DirectoryDoesNotExist()
  415. {
  416. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  417. var contentToAppend = "Forever&\u0116ver";
  418. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  419. {
  420. client.Connect();
  421. if (client.Exists(remoteFile))
  422. {
  423. client.DeleteFile(remoteFile);
  424. }
  425. try
  426. {
  427. client.AppendAllText(remoteFile, contentToAppend);
  428. Assert.Fail();
  429. }
  430. catch (SftpPathNotFoundException ex)
  431. {
  432. Assert.IsNull(ex.InnerException);
  433. Assert.AreEqual("No such file", ex.Message);
  434. }
  435. finally
  436. {
  437. if (client.Exists(remoteFile))
  438. {
  439. client.DeleteFile(remoteFile);
  440. }
  441. }
  442. }
  443. }
  444. [TestMethod]
  445. public void Sftp_AppendAllText_NoEncoding_FileDoesNotExist()
  446. {
  447. var contentToAppend = "Forever&\u0116ver";
  448. var expectedContent = contentToAppend;
  449. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  450. {
  451. client.Connect();
  452. var remoteFile = GenerateUniqueRemoteFileName();
  453. if (client.Exists(remoteFile))
  454. {
  455. client.DeleteFile(remoteFile);
  456. }
  457. try
  458. {
  459. client.AppendAllText(remoteFile, contentToAppend);
  460. var text = client.ReadAllText(remoteFile);
  461. Assert.AreEqual(expectedContent, text);
  462. // ensure we didn't write an UTF-8 BOM
  463. using (var fs = client.OpenRead(remoteFile))
  464. {
  465. var firstByte = fs.ReadByte();
  466. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  467. }
  468. }
  469. finally
  470. {
  471. if (client.Exists(remoteFile))
  472. {
  473. client.DeleteFile(remoteFile);
  474. }
  475. }
  476. }
  477. }
  478. [TestMethod]
  479. public void Sftp_AppendText_NoEncoding_ExistingFile()
  480. {
  481. var initialContent = "\u0100ert & Ann";
  482. var contentToAppend = "Forever&\u0116ver";
  483. var expectedContent = initialContent + contentToAppend;
  484. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  485. {
  486. client.Connect();
  487. var remoteFile = GenerateUniqueRemoteFileName();
  488. if (client.Exists(remoteFile))
  489. {
  490. client.DeleteFile(remoteFile);
  491. }
  492. try
  493. {
  494. client.WriteAllText(remoteFile, initialContent);
  495. using (var sw = client.AppendText(remoteFile))
  496. {
  497. sw.Write(contentToAppend);
  498. }
  499. var text = client.ReadAllText(remoteFile);
  500. Assert.AreEqual(expectedContent, text);
  501. // ensure we didn't write an UTF-8 BOM
  502. using (var fs = client.OpenRead(remoteFile))
  503. {
  504. var firstByte = fs.ReadByte();
  505. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  506. }
  507. }
  508. finally
  509. {
  510. if (client.Exists(remoteFile))
  511. {
  512. client.DeleteFile(remoteFile);
  513. }
  514. }
  515. }
  516. }
  517. [TestMethod]
  518. public void Sftp_AppendText_NoEncoding_DirectoryDoesNotExist()
  519. {
  520. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  521. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  522. {
  523. client.Connect();
  524. if (client.Exists(remoteFile))
  525. {
  526. client.DeleteFile(remoteFile);
  527. }
  528. StreamWriter sw = null;
  529. try
  530. {
  531. sw = client.AppendText(remoteFile);
  532. Assert.Fail();
  533. }
  534. catch (SftpPathNotFoundException ex)
  535. {
  536. Assert.IsNull(ex.InnerException);
  537. Assert.AreEqual("No such file", ex.Message);
  538. }
  539. finally
  540. {
  541. sw?.Dispose();
  542. if (client.Exists(remoteFile))
  543. {
  544. client.DeleteFile(remoteFile);
  545. }
  546. }
  547. }
  548. }
  549. [TestMethod]
  550. public void Sftp_AppendText_NoEncoding_FileDoesNotExist()
  551. {
  552. var contentToAppend = "\u0100ert & Ann";
  553. var expectedContent = contentToAppend;
  554. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  555. {
  556. client.Connect();
  557. var remoteFile = GenerateUniqueRemoteFileName();
  558. if (client.Exists(remoteFile))
  559. {
  560. client.DeleteFile(remoteFile);
  561. }
  562. try
  563. {
  564. using (var sw = client.AppendText(remoteFile))
  565. {
  566. sw.Write(contentToAppend);
  567. }
  568. // ensure we didn't write an UTF-8 BOM
  569. using (var fs = client.OpenRead(remoteFile))
  570. {
  571. var firstByte = fs.ReadByte();
  572. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  573. }
  574. }
  575. finally
  576. {
  577. if (client.Exists(remoteFile))
  578. {
  579. client.DeleteFile(remoteFile);
  580. }
  581. }
  582. }
  583. }
  584. [TestMethod]
  585. public void Sftp_AppendAllLines_Encoding_ExistingFile()
  586. {
  587. var initialContent = "\u0100ert & Ann";
  588. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  589. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  590. Environment.NewLine;
  591. var encoding = GetRandomEncoding();
  592. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  593. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  594. {
  595. client.Connect();
  596. var remoteFile = GenerateUniqueRemoteFileName();
  597. if (client.Exists(remoteFile))
  598. {
  599. client.DeleteFile(remoteFile);
  600. }
  601. try
  602. {
  603. client.WriteAllText(remoteFile, initialContent, encoding);
  604. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  605. var text = client.ReadAllText(remoteFile, encoding);
  606. Assert.AreEqual(expectedContent, text);
  607. using (var fs = client.OpenRead(remoteFile))
  608. {
  609. var actualBytes = new byte[fs.Length];
  610. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  611. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  612. }
  613. }
  614. finally
  615. {
  616. if (client.Exists(remoteFile))
  617. {
  618. client.DeleteFile(remoteFile);
  619. }
  620. }
  621. }
  622. }
  623. [TestMethod]
  624. public void Sftp_AppendAllLines_Encoding_DirectoryDoesNotExist()
  625. {
  626. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  627. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  628. var encoding = GetRandomEncoding();
  629. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  630. {
  631. client.Connect();
  632. if (client.Exists(remoteFile))
  633. {
  634. client.DeleteFile(remoteFile);
  635. }
  636. try
  637. {
  638. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  639. Assert.Fail();
  640. }
  641. catch (SftpPathNotFoundException ex)
  642. {
  643. Assert.IsNull(ex.InnerException);
  644. Assert.AreEqual("No such file", ex.Message);
  645. }
  646. finally
  647. {
  648. if (client.Exists(remoteFile))
  649. {
  650. client.DeleteFile(remoteFile);
  651. }
  652. }
  653. }
  654. }
  655. [TestMethod]
  656. public void Sftp_AppendAllLines_Encoding_FileDoesNotExist()
  657. {
  658. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  659. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  660. var encoding = GetRandomEncoding();
  661. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  662. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  663. {
  664. client.Connect();
  665. var remoteFile = GenerateUniqueRemoteFileName();
  666. if (client.Exists(remoteFile))
  667. {
  668. client.DeleteFile(remoteFile);
  669. }
  670. try
  671. {
  672. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  673. var text = client.ReadAllText(remoteFile, encoding);
  674. Assert.AreEqual(expectedContent, text);
  675. using (var fs = client.OpenRead(remoteFile))
  676. {
  677. var actualBytes = new byte[fs.Length];
  678. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  679. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  680. }
  681. }
  682. finally
  683. {
  684. if (client.Exists(remoteFile))
  685. {
  686. client.DeleteFile(remoteFile);
  687. }
  688. }
  689. }
  690. }
  691. [TestMethod]
  692. public void Sftp_AppendAllText_Encoding_ExistingFile()
  693. {
  694. var initialContent = "\u0100ert & Ann";
  695. var contentToAppend = "Forever&\u0116ver";
  696. var expectedContent = initialContent + contentToAppend;
  697. var encoding = GetRandomEncoding();
  698. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  699. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  700. {
  701. client.Connect();
  702. var remoteFile = GenerateUniqueRemoteFileName();
  703. if (client.Exists(remoteFile))
  704. {
  705. client.DeleteFile(remoteFile);
  706. }
  707. try
  708. {
  709. client.WriteAllText(remoteFile, initialContent, encoding);
  710. client.AppendAllText(remoteFile, contentToAppend, encoding);
  711. var text = client.ReadAllText(remoteFile, encoding);
  712. Assert.AreEqual(expectedContent, text);
  713. using (var fs = client.OpenRead(remoteFile))
  714. {
  715. var actualBytes = new byte[fs.Length];
  716. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  717. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  718. }
  719. }
  720. finally
  721. {
  722. if (client.Exists(remoteFile))
  723. {
  724. client.DeleteFile(remoteFile);
  725. }
  726. }
  727. }
  728. }
  729. [TestMethod]
  730. public void Sftp_AppendAllText_Encoding_DirectoryDoesNotExist()
  731. {
  732. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  733. const string contentToAppend = "Forever&\u0116ver";
  734. var encoding = GetRandomEncoding();
  735. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  736. {
  737. client.Connect();
  738. if (client.Exists(remoteFile))
  739. {
  740. client.DeleteFile(remoteFile);
  741. }
  742. try
  743. {
  744. client.AppendAllText(remoteFile, contentToAppend, encoding);
  745. Assert.Fail();
  746. }
  747. catch (SftpPathNotFoundException ex)
  748. {
  749. Assert.IsNull(ex.InnerException);
  750. Assert.AreEqual("No such file", ex.Message);
  751. }
  752. finally
  753. {
  754. if (client.Exists(remoteFile))
  755. {
  756. client.DeleteFile(remoteFile);
  757. }
  758. }
  759. }
  760. }
  761. [TestMethod]
  762. public void Sftp_AppendAllText_Encoding_FileDoesNotExist()
  763. {
  764. const string contentToAppend = "Forever&\u0116ver";
  765. var expectedContent = contentToAppend;
  766. var encoding = GetRandomEncoding();
  767. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  768. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  769. {
  770. client.Connect();
  771. var remoteFile = GenerateUniqueRemoteFileName();
  772. if (client.Exists(remoteFile))
  773. {
  774. client.DeleteFile(remoteFile);
  775. }
  776. try
  777. {
  778. client.AppendAllText(remoteFile, contentToAppend, encoding);
  779. var text = client.ReadAllText(remoteFile, encoding);
  780. Assert.AreEqual(expectedContent, text);
  781. using (var fs = client.OpenRead(remoteFile))
  782. {
  783. var actualBytes = new byte[fs.Length];
  784. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  785. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  786. }
  787. }
  788. finally
  789. {
  790. if (client.Exists(remoteFile))
  791. {
  792. client.DeleteFile(remoteFile);
  793. }
  794. }
  795. }
  796. }
  797. [TestMethod]
  798. public void Sftp_AppendText_Encoding_ExistingFile()
  799. {
  800. const string initialContent = "\u0100ert & Ann";
  801. const string contentToAppend = "Forever&\u0116ver";
  802. var expectedContent = initialContent + contentToAppend;
  803. var encoding = GetRandomEncoding();
  804. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  805. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  806. {
  807. client.Connect();
  808. var remoteFile = GenerateUniqueRemoteFileName();
  809. if (client.Exists(remoteFile))
  810. {
  811. client.DeleteFile(remoteFile);
  812. }
  813. try
  814. {
  815. client.WriteAllText(remoteFile, initialContent, encoding);
  816. using (var sw = client.AppendText(remoteFile, encoding))
  817. {
  818. sw.Write(contentToAppend);
  819. }
  820. var text = client.ReadAllText(remoteFile, encoding);
  821. Assert.AreEqual(expectedContent, text);
  822. using (var fs = client.OpenRead(remoteFile))
  823. {
  824. var actualBytes = new byte[fs.Length];
  825. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  826. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  827. }
  828. }
  829. finally
  830. {
  831. if (client.Exists(remoteFile))
  832. {
  833. client.DeleteFile(remoteFile);
  834. }
  835. }
  836. }
  837. }
  838. [TestMethod]
  839. public void Sftp_AppendText_Encoding_DirectoryDoesNotExist()
  840. {
  841. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  842. var encoding = GetRandomEncoding();
  843. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  844. {
  845. client.Connect();
  846. if (client.Exists(remoteFile))
  847. {
  848. client.DeleteFile(remoteFile);
  849. }
  850. StreamWriter sw = null;
  851. try
  852. {
  853. sw = client.AppendText(remoteFile, encoding);
  854. Assert.Fail();
  855. }
  856. catch (SftpPathNotFoundException ex)
  857. {
  858. Assert.IsNull(ex.InnerException);
  859. Assert.AreEqual("No such file", ex.Message);
  860. }
  861. finally
  862. {
  863. sw?.Dispose();
  864. if (client.Exists(remoteFile))
  865. {
  866. client.DeleteFile(remoteFile);
  867. }
  868. }
  869. }
  870. }
  871. [TestMethod]
  872. public void Sftp_AppendText_Encoding_FileDoesNotExist()
  873. {
  874. var encoding = GetRandomEncoding();
  875. const string contentToAppend = "\u0100ert & Ann";
  876. var expectedBytes = GetBytesWithPreamble(contentToAppend, encoding);
  877. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  878. {
  879. client.Connect();
  880. var remoteFile = GenerateUniqueRemoteFileName();
  881. if (client.Exists(remoteFile))
  882. {
  883. client.DeleteFile(remoteFile);
  884. }
  885. try
  886. {
  887. using (var sw = client.AppendText(remoteFile, encoding))
  888. {
  889. sw.Write(contentToAppend);
  890. }
  891. using (var fs = client.OpenRead(remoteFile))
  892. {
  893. var actualBytes = new byte[fs.Length];
  894. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  895. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  896. }
  897. }
  898. finally
  899. {
  900. if (client.Exists(remoteFile))
  901. {
  902. client.DeleteFile(remoteFile);
  903. }
  904. }
  905. }
  906. }
  907. [TestMethod]
  908. public void Sftp_CreateText_NoEncoding_ExistingFile()
  909. {
  910. var encoding = new UTF8Encoding(false, true);
  911. const string initialContent = "\u0100ert & Ann";
  912. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  913. const string newContent = "\u0116ver";
  914. const string expectedContent = "\u0116ver" + " & Ann";
  915. var expectedContentBytes = GetBytesWithPreamble(expectedContent, encoding);
  916. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  917. {
  918. client.Connect();
  919. var remoteFile = GenerateUniqueRemoteFileName();
  920. if (client.Exists(remoteFile))
  921. {
  922. client.DeleteFile(remoteFile);
  923. }
  924. try
  925. {
  926. client.WriteAllText(remoteFile, initialContent);
  927. using (client.CreateText(remoteFile))
  928. {
  929. }
  930. // verify that original content is left untouched
  931. using (var fs = client.OpenRead(remoteFile))
  932. {
  933. var actualBytes = new byte[fs.Length];
  934. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  935. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  936. }
  937. // write content that is less bytes than original content
  938. using (var sw = client.CreateText(remoteFile))
  939. {
  940. sw.Write(newContent);
  941. }
  942. // verify that original content is only partially overwritten
  943. var text = client.ReadAllText(remoteFile);
  944. Assert.AreEqual(expectedContent, text);
  945. using (var fs = client.OpenRead(remoteFile))
  946. {
  947. var actualBytes = new byte[fs.Length];
  948. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  949. Assert.IsTrue(expectedContentBytes.IsEqualTo(actualBytes));
  950. }
  951. }
  952. finally
  953. {
  954. if (client.Exists(remoteFile))
  955. {
  956. client.DeleteFile(remoteFile);
  957. }
  958. }
  959. }
  960. }
  961. [TestMethod]
  962. public void Sftp_CreateText_NoEncoding_DirectoryDoesNotExist()
  963. {
  964. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  965. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  966. {
  967. client.Connect();
  968. if (client.Exists(remoteFile))
  969. {
  970. client.DeleteFile(remoteFile);
  971. }
  972. StreamWriter sw = null;
  973. try
  974. {
  975. sw = client.CreateText(remoteFile);
  976. Assert.Fail();
  977. }
  978. catch (SftpPathNotFoundException ex)
  979. {
  980. Assert.IsNull(ex.InnerException);
  981. Assert.AreEqual("No such file", ex.Message);
  982. }
  983. finally
  984. {
  985. sw?.Dispose();
  986. if (client.Exists(remoteFile))
  987. {
  988. client.DeleteFile(remoteFile);
  989. }
  990. }
  991. }
  992. }
  993. [TestMethod]
  994. public void Sftp_CreateText_NoEncoding_FileDoesNotExist()
  995. {
  996. var encoding = new UTF8Encoding(false, true);
  997. var initialContent = "\u0100ert & Ann";
  998. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  999. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1000. {
  1001. client.Connect();
  1002. var remoteFile = GenerateUniqueRemoteFileName();
  1003. if (client.Exists(remoteFile))
  1004. {
  1005. client.DeleteFile(remoteFile);
  1006. }
  1007. try
  1008. {
  1009. using (client.CreateText(remoteFile))
  1010. {
  1011. }
  1012. // verify that empty file was created
  1013. Assert.IsTrue(client.Exists(remoteFile));
  1014. var file = client.GetAttributes(remoteFile);
  1015. Assert.AreEqual(0, file.Size);
  1016. client.DeleteFile(remoteFile);
  1017. using (var sw = client.CreateText(remoteFile))
  1018. {
  1019. sw.Write(initialContent);
  1020. }
  1021. // verify that content is written to file
  1022. var text = client.ReadAllText(remoteFile);
  1023. Assert.AreEqual(initialContent, text);
  1024. using (var fs = client.OpenRead(remoteFile))
  1025. {
  1026. var actualBytes = new byte[fs.Length];
  1027. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1028. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1029. }
  1030. }
  1031. finally
  1032. {
  1033. if (client.Exists(remoteFile))
  1034. {
  1035. client.DeleteFile(remoteFile);
  1036. }
  1037. }
  1038. }
  1039. }
  1040. [TestMethod]
  1041. public void Sftp_CreateText_Encoding_ExistingFile()
  1042. {
  1043. var encoding = GetRandomEncoding();
  1044. var initialContent = "\u0100ert & Ann";
  1045. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1046. var newContent = "\u0116ver";
  1047. var expectedContent = "\u0116ver" + " & Ann";
  1048. var expectedContentBytes = GetBytesWithPreamble(expectedContent, encoding);
  1049. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1050. {
  1051. client.Connect();
  1052. var remoteFile = GenerateUniqueRemoteFileName();
  1053. if (client.Exists(remoteFile))
  1054. {
  1055. client.DeleteFile(remoteFile);
  1056. }
  1057. try
  1058. {
  1059. client.WriteAllText(remoteFile, initialContent, encoding);
  1060. using (client.CreateText(remoteFile))
  1061. {
  1062. }
  1063. // verify that original content is left untouched
  1064. using (var fs = client.OpenRead(remoteFile))
  1065. {
  1066. var actualBytes = new byte[fs.Length];
  1067. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1068. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1069. }
  1070. // write content that is less bytes than original content
  1071. using (var sw = client.CreateText(remoteFile, encoding))
  1072. {
  1073. sw.Write(newContent);
  1074. }
  1075. // verify that original content is only partially overwritten
  1076. var text = client.ReadAllText(remoteFile, encoding);
  1077. Assert.AreEqual(expectedContent, text);
  1078. using (var fs = client.OpenRead(remoteFile))
  1079. {
  1080. var actualBytes = new byte[fs.Length];
  1081. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1082. Assert.IsTrue(expectedContentBytes.IsEqualTo(actualBytes));
  1083. }
  1084. }
  1085. finally
  1086. {
  1087. if (client.Exists(remoteFile))
  1088. {
  1089. client.DeleteFile(remoteFile);
  1090. }
  1091. }
  1092. }
  1093. }
  1094. [TestMethod]
  1095. public void Sftp_CreateText_Encoding_DirectoryDoesNotExist()
  1096. {
  1097. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1098. var encoding = GetRandomEncoding();
  1099. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1100. {
  1101. client.Connect();
  1102. if (client.Exists(remoteFile))
  1103. {
  1104. client.DeleteFile(remoteFile);
  1105. }
  1106. StreamWriter sw = null;
  1107. try
  1108. {
  1109. sw = client.CreateText(remoteFile, encoding);
  1110. Assert.Fail();
  1111. }
  1112. catch (SftpPathNotFoundException ex)
  1113. {
  1114. Assert.IsNull(ex.InnerException);
  1115. Assert.AreEqual("No such file", ex.Message);
  1116. }
  1117. finally
  1118. {
  1119. sw?.Dispose();
  1120. if (client.Exists(remoteFile))
  1121. {
  1122. client.DeleteFile(remoteFile);
  1123. }
  1124. }
  1125. }
  1126. }
  1127. [TestMethod]
  1128. public void Sftp_CreateText_Encoding_FileDoesNotExist()
  1129. {
  1130. var encoding = GetRandomEncoding();
  1131. var initialContent = "\u0100ert & Ann";
  1132. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1133. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1134. {
  1135. client.Connect();
  1136. var remoteFile = GenerateUniqueRemoteFileName();
  1137. if (client.Exists(remoteFile))
  1138. {
  1139. client.DeleteFile(remoteFile);
  1140. }
  1141. try
  1142. {
  1143. using (client.CreateText(remoteFile, encoding))
  1144. {
  1145. }
  1146. // verify that file containing only preamble was created
  1147. Assert.IsTrue(client.Exists(remoteFile));
  1148. var file = client.GetAttributes(remoteFile);
  1149. Assert.AreEqual(encoding.GetPreamble().Length, file.Size);
  1150. client.DeleteFile(remoteFile);
  1151. using (var sw = client.CreateText(remoteFile, encoding))
  1152. {
  1153. sw.Write(initialContent);
  1154. }
  1155. // verify that content is written to file
  1156. var text = client.ReadAllText(remoteFile, encoding);
  1157. Assert.AreEqual(initialContent, text);
  1158. using (var fs = client.OpenRead(remoteFile))
  1159. {
  1160. var actualBytes = new byte[fs.Length];
  1161. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1162. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  1163. }
  1164. }
  1165. finally
  1166. {
  1167. if (client.Exists(remoteFile))
  1168. {
  1169. client.DeleteFile(remoteFile);
  1170. }
  1171. }
  1172. }
  1173. }
  1174. [TestMethod]
  1175. public void Sftp_DownloadFile_FileDoesNotExist()
  1176. {
  1177. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1178. {
  1179. client.Connect();
  1180. var remoteFile = GenerateUniqueRemoteFileName();
  1181. if (client.Exists(remoteFile))
  1182. {
  1183. client.DeleteFile(remoteFile);
  1184. }
  1185. using (var ms = new MemoryStream())
  1186. {
  1187. try
  1188. {
  1189. client.DownloadFile(remoteFile, ms);
  1190. Assert.Fail();
  1191. }
  1192. catch (SftpPathNotFoundException ex)
  1193. {
  1194. Assert.IsNull(ex.InnerException);
  1195. Assert.AreEqual("No such file", ex.Message);
  1196. // ensure file was not created by us
  1197. Assert.IsFalse(client.Exists(remoteFile));
  1198. }
  1199. finally
  1200. {
  1201. if (client.Exists(remoteFile))
  1202. {
  1203. client.DeleteFile(remoteFile);
  1204. }
  1205. }
  1206. }
  1207. }
  1208. }
  1209. [TestMethod]
  1210. public void Sftp_ReadAllBytes_ExistingFile()
  1211. {
  1212. var encoding = GetRandomEncoding();
  1213. var content = "\u0100ert & Ann";
  1214. var contentBytes = GetBytesWithPreamble(content, encoding);
  1215. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1216. {
  1217. client.Connect();
  1218. var remoteFile = GenerateUniqueRemoteFileName();
  1219. if (client.Exists(remoteFile))
  1220. {
  1221. client.DeleteFile(remoteFile);
  1222. }
  1223. try
  1224. {
  1225. client.WriteAllText(remoteFile, content, encoding);
  1226. var actualBytes = client.ReadAllBytes(remoteFile);
  1227. Assert.IsTrue(contentBytes.IsEqualTo(actualBytes));
  1228. }
  1229. finally
  1230. {
  1231. if (client.Exists(remoteFile))
  1232. {
  1233. client.DeleteFile(remoteFile);
  1234. }
  1235. }
  1236. }
  1237. }
  1238. [TestMethod]
  1239. public void Sftp_ReadAllBytes_FileDoesNotExist()
  1240. {
  1241. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1242. {
  1243. client.Connect();
  1244. var remoteFile = GenerateUniqueRemoteFileName();
  1245. if (client.Exists(remoteFile))
  1246. {
  1247. client.DeleteFile(remoteFile);
  1248. }
  1249. try
  1250. {
  1251. client.ReadAllBytes(remoteFile);
  1252. Assert.Fail();
  1253. }
  1254. catch (SftpPathNotFoundException ex)
  1255. {
  1256. Assert.IsNull(ex.InnerException);
  1257. Assert.AreEqual("No such file", ex.Message);
  1258. // ensure file was not created by us
  1259. Assert.IsFalse(client.Exists(remoteFile));
  1260. }
  1261. finally
  1262. {
  1263. if (client.Exists(remoteFile))
  1264. {
  1265. client.DeleteFile(remoteFile);
  1266. }
  1267. }
  1268. }
  1269. }
  1270. [TestMethod]
  1271. public void Sftp_ReadAllLines_NoEncoding_ExistingFile()
  1272. {
  1273. var encoding = new UTF8Encoding(false, true);
  1274. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1275. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1276. encoding);
  1277. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1278. {
  1279. client.Connect();
  1280. var remoteFile = GenerateUniqueRemoteFileName();
  1281. if (client.Exists(remoteFile))
  1282. {
  1283. client.DeleteFile(remoteFile);
  1284. }
  1285. try
  1286. {
  1287. using (var sw = client.AppendText(remoteFile))
  1288. {
  1289. for (var i = 0; i < lines.Length; i++)
  1290. {
  1291. sw.WriteLine(lines[i]);
  1292. }
  1293. }
  1294. var actualLines = client.ReadAllLines(remoteFile);
  1295. Assert.IsNotNull(actualLines);
  1296. Assert.AreEqual(lines.Length, actualLines.Length);
  1297. for (var i = 0; i < lines.Length; i++)
  1298. {
  1299. Assert.AreEqual(lines[i], actualLines[i]);
  1300. }
  1301. using (var fs = client.OpenRead(remoteFile))
  1302. {
  1303. var actualBytes = new byte[fs.Length];
  1304. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1305. Assert.IsTrue(linesBytes.IsEqualTo(actualBytes));
  1306. }
  1307. }
  1308. finally
  1309. {
  1310. if (client.Exists(remoteFile))
  1311. {
  1312. client.DeleteFile(remoteFile);
  1313. }
  1314. }
  1315. }
  1316. }
  1317. [TestMethod]
  1318. public void Sftp_ReadAllLines_NoEncoding_FileDoesNotExist()
  1319. {
  1320. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1321. {
  1322. client.Connect();
  1323. var remoteFile = GenerateUniqueRemoteFileName();
  1324. if (client.Exists(remoteFile))
  1325. {
  1326. client.DeleteFile(remoteFile);
  1327. }
  1328. try
  1329. {
  1330. client.ReadAllLines(remoteFile);
  1331. Assert.Fail();
  1332. }
  1333. catch (SftpPathNotFoundException ex)
  1334. {
  1335. Assert.IsNull(ex.InnerException);
  1336. Assert.AreEqual("No such file", ex.Message);
  1337. // ensure file was not created by us
  1338. Assert.IsFalse(client.Exists(remoteFile));
  1339. }
  1340. finally
  1341. {
  1342. if (client.Exists(remoteFile))
  1343. {
  1344. client.DeleteFile(remoteFile);
  1345. }
  1346. }
  1347. }
  1348. }
  1349. [TestMethod]
  1350. public void Sftp_ReadAllLines_Encoding_ExistingFile()
  1351. {
  1352. var encoding = GetRandomEncoding();
  1353. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1354. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1355. encoding);
  1356. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1357. {
  1358. client.Connect();
  1359. var remoteFile = GenerateUniqueRemoteFileName();
  1360. if (client.Exists(remoteFile))
  1361. {
  1362. client.DeleteFile(remoteFile);
  1363. }
  1364. try
  1365. {
  1366. using (var sw = client.AppendText(remoteFile, encoding))
  1367. {
  1368. for (var i = 0; i < lines.Length; i++)
  1369. {
  1370. sw.WriteLine(lines[i]);
  1371. }
  1372. }
  1373. var actualLines = client.ReadAllLines(remoteFile, encoding);
  1374. Assert.IsNotNull(actualLines);
  1375. Assert.AreEqual(lines.Length, actualLines.Length);
  1376. for (var i = 0; i < lines.Length; i++)
  1377. {
  1378. Assert.AreEqual(lines[i], actualLines[i]);
  1379. }
  1380. using (var fs = client.OpenRead(remoteFile))
  1381. {
  1382. var actualBytes = new byte[fs.Length];
  1383. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1384. Assert.IsTrue(linesBytes.IsEqualTo(actualBytes));
  1385. }
  1386. }
  1387. finally
  1388. {
  1389. if (client.Exists(remoteFile))
  1390. {
  1391. client.DeleteFile(remoteFile);
  1392. }
  1393. }
  1394. }
  1395. }
  1396. [TestMethod]
  1397. public void Sftp_ReadAllLines_Encoding_FileDoesNotExist()
  1398. {
  1399. var encoding = GetRandomEncoding();
  1400. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1401. {
  1402. client.Connect();
  1403. var remoteFile = GenerateUniqueRemoteFileName();
  1404. if (client.Exists(remoteFile))
  1405. {
  1406. client.DeleteFile(remoteFile);
  1407. }
  1408. try
  1409. {
  1410. client.ReadAllLines(remoteFile, encoding);
  1411. Assert.Fail();
  1412. }
  1413. catch (SftpPathNotFoundException ex)
  1414. {
  1415. Assert.IsNull(ex.InnerException);
  1416. Assert.AreEqual("No such file", ex.Message);
  1417. // ensure file was not created by us
  1418. Assert.IsFalse(client.Exists(remoteFile));
  1419. }
  1420. finally
  1421. {
  1422. if (client.Exists(remoteFile))
  1423. {
  1424. client.DeleteFile(remoteFile);
  1425. }
  1426. }
  1427. }
  1428. }
  1429. [TestMethod]
  1430. public void Sftp_ReadAllText_NoEncoding_ExistingFile()
  1431. {
  1432. var encoding = new UTF8Encoding(false, true);
  1433. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1434. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1435. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1436. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1437. {
  1438. client.Connect();
  1439. var remoteFile = GenerateUniqueRemoteFileName();
  1440. if (client.Exists(remoteFile))
  1441. {
  1442. client.DeleteFile(remoteFile);
  1443. }
  1444. try
  1445. {
  1446. using (var sw = client.AppendText(remoteFile))
  1447. {
  1448. for (var i = 0; i < lines.Length; i++)
  1449. {
  1450. sw.WriteLine(lines[i]);
  1451. }
  1452. }
  1453. var actualText = client.ReadAllText(remoteFile);
  1454. Assert.AreEqual(expectedText, actualText);
  1455. using (var fs = client.OpenRead(remoteFile))
  1456. {
  1457. var actualBytes = new byte[fs.Length];
  1458. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1459. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  1460. }
  1461. }
  1462. finally
  1463. {
  1464. if (client.Exists(remoteFile))
  1465. {
  1466. client.DeleteFile(remoteFile);
  1467. }
  1468. }
  1469. }
  1470. }
  1471. [TestMethod]
  1472. public void Sftp_ReadAllText_NoEncoding_FileDoesNotExist()
  1473. {
  1474. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1475. {
  1476. client.Connect();
  1477. var remoteFile = GenerateUniqueRemoteFileName();
  1478. if (client.Exists(remoteFile))
  1479. {
  1480. client.DeleteFile(remoteFile);
  1481. }
  1482. try
  1483. {
  1484. client.ReadAllText(remoteFile);
  1485. Assert.Fail();
  1486. }
  1487. catch (SftpPathNotFoundException ex)
  1488. {
  1489. Assert.IsNull(ex.InnerException);
  1490. Assert.AreEqual("No such file", ex.Message);
  1491. // ensure file was not created by us
  1492. Assert.IsFalse(client.Exists(remoteFile));
  1493. }
  1494. finally
  1495. {
  1496. if (client.Exists(remoteFile))
  1497. {
  1498. client.DeleteFile(remoteFile);
  1499. }
  1500. }
  1501. }
  1502. }
  1503. [TestMethod]
  1504. public void Sftp_ReadAllText_Encoding_ExistingFile()
  1505. {
  1506. var encoding = GetRandomEncoding();
  1507. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1508. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1509. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1510. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1511. {
  1512. client.Connect();
  1513. var remoteFile = GenerateUniqueRemoteFileName();
  1514. if (client.Exists(remoteFile))
  1515. {
  1516. client.DeleteFile(remoteFile);
  1517. }
  1518. try
  1519. {
  1520. using (var sw = client.AppendText(remoteFile, encoding))
  1521. {
  1522. for (var i = 0; i < lines.Length; i++)
  1523. {
  1524. sw.WriteLine(lines[i]);
  1525. }
  1526. }
  1527. var actualText = client.ReadAllText(remoteFile, encoding);
  1528. Assert.AreEqual(expectedText, actualText);
  1529. using (var fs = client.OpenRead(remoteFile))
  1530. {
  1531. var actualBytes = new byte[fs.Length];
  1532. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1533. Assert.IsTrue(expectedBytes.IsEqualTo(actualBytes));
  1534. }
  1535. }
  1536. finally
  1537. {
  1538. if (client.Exists(remoteFile))
  1539. {
  1540. client.DeleteFile(remoteFile);
  1541. }
  1542. }
  1543. }
  1544. }
  1545. [TestMethod]
  1546. public void Sftp_ReadAllText_Encoding_FileDoesNotExist()
  1547. {
  1548. var encoding = GetRandomEncoding();
  1549. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1550. {
  1551. client.Connect();
  1552. var remoteFile = GenerateUniqueRemoteFileName();
  1553. if (client.Exists(remoteFile))
  1554. {
  1555. client.DeleteFile(remoteFile);
  1556. }
  1557. try
  1558. {
  1559. client.ReadAllText(remoteFile, encoding);
  1560. Assert.Fail();
  1561. }
  1562. catch (SftpPathNotFoundException ex)
  1563. {
  1564. Assert.IsNull(ex.InnerException);
  1565. Assert.AreEqual("No such file", ex.Message);
  1566. // ensure file was not created by us
  1567. Assert.IsFalse(client.Exists(remoteFile));
  1568. }
  1569. finally
  1570. {
  1571. if (client.Exists(remoteFile))
  1572. {
  1573. client.DeleteFile(remoteFile);
  1574. }
  1575. }
  1576. }
  1577. }
  1578. [TestMethod]
  1579. public void Sftp_ReadLines_NoEncoding_ExistingFile()
  1580. {
  1581. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1582. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1583. {
  1584. client.Connect();
  1585. var remoteFile = GenerateUniqueRemoteFileName();
  1586. if (client.Exists(remoteFile))
  1587. {
  1588. client.DeleteFile(remoteFile);
  1589. }
  1590. try
  1591. {
  1592. using (var sw = client.AppendText(remoteFile))
  1593. {
  1594. for (var i = 0; i < lines.Length; i++)
  1595. {
  1596. sw.WriteLine(lines[i]);
  1597. }
  1598. }
  1599. var actualLines = client.ReadLines(remoteFile);
  1600. Assert.IsNotNull(actualLines);
  1601. var actualLinesEnum = actualLines.GetEnumerator();
  1602. for (var i = 0; i < lines.Length; i++)
  1603. {
  1604. Assert.IsTrue(actualLinesEnum.MoveNext());
  1605. var actualLine = actualLinesEnum.Current;
  1606. Assert.AreEqual(lines[i], actualLine);
  1607. }
  1608. Assert.IsFalse(actualLinesEnum.MoveNext());
  1609. }
  1610. finally
  1611. {
  1612. if (client.Exists(remoteFile))
  1613. {
  1614. client.DeleteFile(remoteFile);
  1615. }
  1616. }
  1617. }
  1618. }
  1619. [TestMethod]
  1620. public void Sftp_ReadLines_NoEncoding_FileDoesNotExist()
  1621. {
  1622. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1623. {
  1624. client.Connect();
  1625. var remoteFile = GenerateUniqueRemoteFileName();
  1626. if (client.Exists(remoteFile))
  1627. {
  1628. client.DeleteFile(remoteFile);
  1629. }
  1630. try
  1631. {
  1632. client.ReadLines(remoteFile);
  1633. Assert.Fail();
  1634. }
  1635. catch (SftpPathNotFoundException ex)
  1636. {
  1637. Assert.IsNull(ex.InnerException);
  1638. Assert.AreEqual("No such file", ex.Message);
  1639. // ensure file was not created by us
  1640. Assert.IsFalse(client.Exists(remoteFile));
  1641. }
  1642. finally
  1643. {
  1644. if (client.Exists(remoteFile))
  1645. {
  1646. client.DeleteFile(remoteFile);
  1647. }
  1648. }
  1649. }
  1650. }
  1651. [TestMethod]
  1652. public void Sftp_ReadLines_Encoding_ExistingFile()
  1653. {
  1654. var encoding = GetRandomEncoding();
  1655. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1656. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1657. {
  1658. client.Connect();
  1659. var remoteFile = GenerateUniqueRemoteFileName();
  1660. if (client.Exists(remoteFile))
  1661. {
  1662. client.DeleteFile(remoteFile);
  1663. }
  1664. try
  1665. {
  1666. using (var sw = client.AppendText(remoteFile, encoding))
  1667. {
  1668. for (var i = 0; i < lines.Length; i++)
  1669. {
  1670. sw.WriteLine(lines[i]);
  1671. }
  1672. }
  1673. var actualLines = client.ReadLines(remoteFile, encoding);
  1674. Assert.IsNotNull(actualLines);
  1675. using (var actualLinesEnum = actualLines.GetEnumerator())
  1676. {
  1677. for (var i = 0; i < lines.Length; i++)
  1678. {
  1679. Assert.IsTrue(actualLinesEnum.MoveNext());
  1680. var actualLine = actualLinesEnum.Current;
  1681. Assert.AreEqual(lines[i], actualLine);
  1682. }
  1683. Assert.IsFalse(actualLinesEnum.MoveNext());
  1684. }
  1685. }
  1686. finally
  1687. {
  1688. if (client.Exists(remoteFile))
  1689. {
  1690. client.DeleteFile(remoteFile);
  1691. }
  1692. }
  1693. }
  1694. }
  1695. [TestMethod]
  1696. public void Sftp_ReadLines_Encoding_FileDoesNotExist()
  1697. {
  1698. var encoding = GetRandomEncoding();
  1699. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1700. {
  1701. client.Connect();
  1702. var remoteFile = GenerateUniqueRemoteFileName();
  1703. if (client.Exists(remoteFile))
  1704. {
  1705. client.DeleteFile(remoteFile);
  1706. }
  1707. try
  1708. {
  1709. client.ReadLines(remoteFile, encoding);
  1710. Assert.Fail();
  1711. }
  1712. catch (SftpPathNotFoundException ex)
  1713. {
  1714. Assert.IsNull(ex.InnerException);
  1715. Assert.AreEqual("No such file", ex.Message);
  1716. // ensure file was not created by us
  1717. Assert.IsFalse(client.Exists(remoteFile));
  1718. }
  1719. finally
  1720. {
  1721. if (client.Exists(remoteFile))
  1722. {
  1723. client.DeleteFile(remoteFile);
  1724. }
  1725. }
  1726. }
  1727. }
  1728. [TestMethod]
  1729. public void Sftp_WriteAllBytes_DirectoryDoesNotExist()
  1730. {
  1731. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1732. var content = GenerateRandom(size: 5);
  1733. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1734. {
  1735. client.Connect();
  1736. if (client.Exists(remoteFile))
  1737. {
  1738. client.DeleteFile(remoteFile);
  1739. }
  1740. try
  1741. {
  1742. client.WriteAllBytes(remoteFile, content);
  1743. Assert.Fail();
  1744. }
  1745. catch (SftpPathNotFoundException ex)
  1746. {
  1747. Assert.IsNull(ex.InnerException);
  1748. Assert.AreEqual("No such file", ex.Message);
  1749. }
  1750. finally
  1751. {
  1752. if (client.Exists(remoteFile))
  1753. {
  1754. client.DeleteFile(remoteFile);
  1755. }
  1756. }
  1757. }
  1758. }
  1759. [TestMethod]
  1760. public void Sftp_WriteAllBytes_ExistingFile()
  1761. {
  1762. var initialContent = GenerateRandom(size: 13);
  1763. var newContent1 = GenerateRandom(size: 5);
  1764. var expectedContent1 = new ArrayBuilder<byte>().Add(newContent1)
  1765. .Add(initialContent, newContent1.Length, initialContent.Length - newContent1.Length)
  1766. .Build();
  1767. var newContent2 = GenerateRandom(size: 50000);
  1768. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1769. {
  1770. client.Connect();
  1771. var remoteFile = GenerateUniqueRemoteFileName();
  1772. if (client.Exists(remoteFile))
  1773. {
  1774. client.DeleteFile(remoteFile);
  1775. }
  1776. try
  1777. {
  1778. using (var fs = client.Create(remoteFile))
  1779. {
  1780. fs.Write(initialContent, offset: 0, initialContent.Length);
  1781. }
  1782. #region Write less bytes than the current content, overwriting part of that content
  1783. client.WriteAllBytes(remoteFile, newContent1);
  1784. var actualContent1 = client.ReadAllBytes(remoteFile);
  1785. Assert.IsTrue(expectedContent1.IsEqualTo(actualContent1));
  1786. #endregion Write less bytes than the initial content, overwriting part of that content
  1787. #region Write more bytes than the current content, overwriting and appending to that content
  1788. client.WriteAllBytes(remoteFile, newContent2);
  1789. var actualContent2 = client.ReadAllBytes(remoteFile);
  1790. Assert.IsTrue(newContent2.IsEqualTo(actualContent2));
  1791. #endregion Write less bytes than the initial content, overwriting part of that content
  1792. }
  1793. finally
  1794. {
  1795. if (client.Exists(remoteFile))
  1796. {
  1797. client.DeleteFile(remoteFile);
  1798. }
  1799. }
  1800. }
  1801. }
  1802. [TestMethod]
  1803. public void Sftp_WriteAllBytes_FileDoesNotExist()
  1804. {
  1805. var content = GenerateRandom(size: 13);
  1806. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1807. {
  1808. client.Connect();
  1809. var remoteFile = GenerateUniqueRemoteFileName();
  1810. if (client.Exists(remoteFile))
  1811. {
  1812. client.DeleteFile(remoteFile);
  1813. }
  1814. try
  1815. {
  1816. client.WriteAllBytes(remoteFile, content);
  1817. using (var fs = client.OpenRead(remoteFile))
  1818. {
  1819. var actualBytes = new byte[fs.Length];
  1820. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1821. Assert.IsTrue(content.IsEqualTo(actualBytes));
  1822. }
  1823. }
  1824. finally
  1825. {
  1826. if (client.Exists(remoteFile))
  1827. {
  1828. client.DeleteFile(remoteFile);
  1829. }
  1830. }
  1831. }
  1832. }
  1833. [TestMethod]
  1834. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_DirectoryDoesNotExist()
  1835. {
  1836. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1837. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1838. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1839. {
  1840. client.Connect();
  1841. if (client.Exists(remoteFile))
  1842. {
  1843. client.DeleteFile(remoteFile);
  1844. }
  1845. try
  1846. {
  1847. client.WriteAllLines(remoteFile, linesToWrite);
  1848. Assert.Fail();
  1849. }
  1850. catch (SftpPathNotFoundException ex)
  1851. {
  1852. Assert.IsNull(ex.InnerException);
  1853. Assert.AreEqual("No such file", ex.Message);
  1854. }
  1855. finally
  1856. {
  1857. if (client.Exists(remoteFile))
  1858. {
  1859. client.DeleteFile(remoteFile);
  1860. }
  1861. }
  1862. }
  1863. }
  1864. [TestMethod]
  1865. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_ExistingFile()
  1866. {
  1867. var encoding = new UTF8Encoding(false, true);
  1868. var initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1869. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1870. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1871. var linesToWrite1Bytes =
  1872. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1873. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  1874. .Add(initialContentBytes,
  1875. linesToWrite1Bytes.Length,
  1876. initialContentBytes.Length - linesToWrite1Bytes.Length)
  1877. .Build();
  1878. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1879. var linesToWrite2Bytes =
  1880. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1881. var expectedBytes2 = linesToWrite2Bytes;
  1882. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1883. {
  1884. client.Connect();
  1885. var remoteFile = GenerateUniqueRemoteFileName();
  1886. if (client.Exists(remoteFile))
  1887. {
  1888. client.DeleteFile(remoteFile);
  1889. }
  1890. try
  1891. {
  1892. // create initial content
  1893. client.WriteAllText(remoteFile, initialContent);
  1894. #region Write less bytes than the current content, overwriting part of that content
  1895. client.WriteAllLines(remoteFile, linesToWrite1);
  1896. using (var fs = client.OpenRead(remoteFile))
  1897. {
  1898. var actualBytes = new byte[fs.Length];
  1899. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1900. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  1901. }
  1902. #endregion Write less bytes than the current content, overwriting part of that content
  1903. #region Write more bytes than the current content, overwriting and appending to that content
  1904. client.WriteAllLines(remoteFile, linesToWrite2);
  1905. using (var fs = client.OpenRead(remoteFile))
  1906. {
  1907. var actualBytes = new byte[fs.Length];
  1908. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1909. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  1910. }
  1911. #endregion Write more bytes than the current content, overwriting and appending to that content
  1912. }
  1913. finally
  1914. {
  1915. if (client.Exists(remoteFile))
  1916. {
  1917. client.DeleteFile(remoteFile);
  1918. }
  1919. }
  1920. }
  1921. }
  1922. [TestMethod]
  1923. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_FileDoesNotExist()
  1924. {
  1925. var encoding = new UTF8Encoding(false, true);
  1926. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1927. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1928. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1929. {
  1930. client.Connect();
  1931. var remoteFile = GenerateUniqueRemoteFileName();
  1932. if (client.Exists(remoteFile))
  1933. {
  1934. client.DeleteFile(remoteFile);
  1935. }
  1936. try
  1937. {
  1938. client.WriteAllLines(remoteFile, linesToWrite);
  1939. using (var fs = client.OpenRead(remoteFile))
  1940. {
  1941. var actualBytes = new byte[fs.Length];
  1942. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  1943. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  1944. }
  1945. }
  1946. finally
  1947. {
  1948. if (client.Exists(remoteFile))
  1949. {
  1950. client.DeleteFile(remoteFile);
  1951. }
  1952. }
  1953. }
  1954. }
  1955. [TestMethod]
  1956. public void Sftp_WriteAllLines_IEnumerable_Encoding_DirectoryDoesNotExist()
  1957. {
  1958. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1959. var encoding = GetRandomEncoding();
  1960. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1961. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1962. {
  1963. client.Connect();
  1964. if (client.Exists(remoteFile))
  1965. {
  1966. client.DeleteFile(remoteFile);
  1967. }
  1968. try
  1969. {
  1970. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1971. Assert.Fail();
  1972. }
  1973. catch (SftpPathNotFoundException ex)
  1974. {
  1975. Assert.IsNull(ex.InnerException);
  1976. Assert.AreEqual("No such file", ex.Message);
  1977. }
  1978. finally
  1979. {
  1980. if (client.Exists(remoteFile))
  1981. {
  1982. client.DeleteFile(remoteFile);
  1983. }
  1984. }
  1985. }
  1986. }
  1987. [TestMethod]
  1988. public void Sftp_WriteAllLines_IEnumerable_Encoding_ExistingFile()
  1989. {
  1990. var encoding = GetRandomEncoding();
  1991. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1992. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1993. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1994. var linesToWrite1Bytes =
  1995. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1996. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  1997. .Add(initialContentBytes,
  1998. linesToWrite1Bytes.Length,
  1999. initialContentBytes.Length - linesToWrite1Bytes.Length)
  2000. .Build();
  2001. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2002. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2003. var expectedBytes2 = linesToWrite2Bytes;
  2004. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2005. {
  2006. client.Connect();
  2007. var remoteFile = GenerateUniqueRemoteFileName();
  2008. if (client.Exists(remoteFile))
  2009. {
  2010. client.DeleteFile(remoteFile);
  2011. }
  2012. try
  2013. {
  2014. // create initial content
  2015. client.WriteAllText(remoteFile, initialContent, encoding);
  2016. #region Write less bytes than the current content, overwriting part of that content
  2017. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2018. using (var fs = client.OpenRead(remoteFile))
  2019. {
  2020. var actualBytes = new byte[fs.Length];
  2021. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2022. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2023. }
  2024. #endregion Write less bytes than the current content, overwriting part of that content
  2025. #region Write more bytes than the current content, overwriting and appending to that content
  2026. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2027. using (var fs = client.OpenRead(remoteFile))
  2028. {
  2029. var actualBytes = new byte[fs.Length];
  2030. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2031. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2032. }
  2033. #endregion Write more bytes than the current content, overwriting and appending to that content
  2034. }
  2035. finally
  2036. {
  2037. if (client.Exists(remoteFile))
  2038. {
  2039. client.DeleteFile(remoteFile);
  2040. }
  2041. }
  2042. }
  2043. }
  2044. [TestMethod]
  2045. public void Sftp_WriteAllLines_IEnumerable_Encoding_FileDoesNotExist()
  2046. {
  2047. var encoding = GetRandomEncoding();
  2048. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2049. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2050. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2051. {
  2052. client.Connect();
  2053. var remoteFile = GenerateUniqueRemoteFileName();
  2054. if (client.Exists(remoteFile))
  2055. {
  2056. client.DeleteFile(remoteFile);
  2057. }
  2058. try
  2059. {
  2060. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2061. using (var fs = client.OpenRead(remoteFile))
  2062. {
  2063. var actualBytes = new byte[fs.Length];
  2064. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2065. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2066. }
  2067. }
  2068. finally
  2069. {
  2070. if (client.Exists(remoteFile))
  2071. {
  2072. client.DeleteFile(remoteFile);
  2073. }
  2074. }
  2075. }
  2076. }
  2077. [TestMethod]
  2078. public void Sftp_WriteAllLines_Array_NoEncoding_DirectoryDoesNotExist()
  2079. {
  2080. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2081. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  2082. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2083. {
  2084. client.Connect();
  2085. if (client.Exists(remoteFile))
  2086. {
  2087. client.DeleteFile(remoteFile);
  2088. }
  2089. try
  2090. {
  2091. client.WriteAllLines(remoteFile, linesToWrite);
  2092. Assert.Fail();
  2093. }
  2094. catch (SftpPathNotFoundException ex)
  2095. {
  2096. Assert.IsNull(ex.InnerException);
  2097. Assert.AreEqual("No such file", ex.Message);
  2098. }
  2099. finally
  2100. {
  2101. if (client.Exists(remoteFile))
  2102. {
  2103. client.DeleteFile(remoteFile);
  2104. }
  2105. }
  2106. }
  2107. }
  2108. [TestMethod]
  2109. public void Sftp_WriteAllLines_Array_NoEncoding_ExistingFile()
  2110. {
  2111. var encoding = new UTF8Encoding(false, true);
  2112. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2113. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2114. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2115. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2116. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  2117. .Add(initialContentBytes, linesToWrite1Bytes.Length, initialContentBytes.Length - linesToWrite1Bytes.Length)
  2118. .Build();
  2119. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2120. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2121. var expectedBytes2 = linesToWrite2Bytes;
  2122. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2123. {
  2124. client.Connect();
  2125. var remoteFile = GenerateUniqueRemoteFileName();
  2126. if (client.Exists(remoteFile))
  2127. {
  2128. client.DeleteFile(remoteFile);
  2129. }
  2130. try
  2131. {
  2132. // create initial content
  2133. client.WriteAllText(remoteFile, initialContent);
  2134. #region Write less bytes than the current content, overwriting part of that content
  2135. client.WriteAllLines(remoteFile, linesToWrite1);
  2136. using (var fs = client.OpenRead(remoteFile))
  2137. {
  2138. var actualBytes = new byte[fs.Length];
  2139. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2140. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2141. }
  2142. #endregion Write less bytes than the current content, overwriting part of that content
  2143. #region Write more bytes than the current content, overwriting and appending to that content
  2144. client.WriteAllLines(remoteFile, linesToWrite2);
  2145. using (var fs = client.OpenRead(remoteFile))
  2146. {
  2147. var actualBytes = new byte[fs.Length];
  2148. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2149. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2150. }
  2151. #endregion Write more bytes than the current content, overwriting and appending to that content
  2152. }
  2153. finally
  2154. {
  2155. if (client.Exists(remoteFile))
  2156. {
  2157. client.DeleteFile(remoteFile);
  2158. }
  2159. }
  2160. }
  2161. }
  2162. [TestMethod]
  2163. public void Sftp_WriteAllLines_Array_NoEncoding_FileDoesNotExist()
  2164. {
  2165. var encoding = new UTF8Encoding(false, true);
  2166. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2167. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2168. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2169. {
  2170. client.Connect();
  2171. var remoteFile = GenerateUniqueRemoteFileName();
  2172. if (client.Exists(remoteFile))
  2173. {
  2174. client.DeleteFile(remoteFile);
  2175. }
  2176. try
  2177. {
  2178. client.WriteAllLines(remoteFile, linesToWrite);
  2179. using (var fs = client.OpenRead(remoteFile))
  2180. {
  2181. var actualBytes = new byte[fs.Length];
  2182. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2183. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2184. }
  2185. }
  2186. finally
  2187. {
  2188. if (client.Exists(remoteFile))
  2189. {
  2190. client.DeleteFile(remoteFile);
  2191. }
  2192. }
  2193. }
  2194. }
  2195. [TestMethod]
  2196. public void Sftp_WriteAllLines_Array_Encoding_DirectoryDoesNotExist()
  2197. {
  2198. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2199. var encoding = GetRandomEncoding();
  2200. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  2201. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2202. {
  2203. client.Connect();
  2204. if (client.Exists(remoteFile))
  2205. {
  2206. client.DeleteFile(remoteFile);
  2207. }
  2208. try
  2209. {
  2210. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2211. Assert.Fail();
  2212. }
  2213. catch (SftpPathNotFoundException ex)
  2214. {
  2215. Assert.IsNull(ex.InnerException);
  2216. Assert.AreEqual("No such file", ex.Message);
  2217. }
  2218. finally
  2219. {
  2220. if (client.Exists(remoteFile))
  2221. {
  2222. client.DeleteFile(remoteFile);
  2223. }
  2224. }
  2225. }
  2226. }
  2227. [TestMethod]
  2228. public void Sftp_WriteAllLines_Array_Encoding_ExistingFile()
  2229. {
  2230. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2231. var encoding = GetRandomEncoding();
  2232. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2233. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2234. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2235. var expectedBytes1 = new ArrayBuilder<byte>().Add(linesToWrite1Bytes)
  2236. .Add(initialContentBytes, linesToWrite1Bytes.Length, initialContentBytes.Length - linesToWrite1Bytes.Length)
  2237. .Build();
  2238. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2239. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2240. var expectedBytes2 = linesToWrite2Bytes;
  2241. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2242. {
  2243. client.Connect();
  2244. var remoteFile = GenerateUniqueRemoteFileName();
  2245. if (client.Exists(remoteFile))
  2246. {
  2247. client.DeleteFile(remoteFile);
  2248. }
  2249. try
  2250. {
  2251. // create initial content
  2252. client.WriteAllText(remoteFile, initialContent, encoding);
  2253. #region Write less bytes than the current content, overwriting part of that content
  2254. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2255. using (var fs = client.OpenRead(remoteFile))
  2256. {
  2257. var actualBytes = new byte[fs.Length];
  2258. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2259. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2260. }
  2261. #endregion Write less bytes than the current content, overwriting part of that content
  2262. #region Write more bytes than the current content, overwriting and appending to that content
  2263. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2264. using (var fs = client.OpenRead(remoteFile))
  2265. {
  2266. var actualBytes = new byte[fs.Length];
  2267. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2268. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2269. }
  2270. #endregion Write more bytes than the current content, overwriting and appending to that content
  2271. }
  2272. finally
  2273. {
  2274. if (client.Exists(remoteFile))
  2275. {
  2276. client.DeleteFile(remoteFile);
  2277. }
  2278. }
  2279. }
  2280. }
  2281. [TestMethod]
  2282. public void Sftp_WriteAllLines_Array_Encoding_FileDoesNotExist()
  2283. {
  2284. var encoding = GetRandomEncoding();
  2285. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2286. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2287. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2288. {
  2289. client.Connect();
  2290. var remoteFile = GenerateUniqueRemoteFileName();
  2291. if (client.Exists(remoteFile))
  2292. {
  2293. client.DeleteFile(remoteFile);
  2294. }
  2295. try
  2296. {
  2297. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2298. using (var fs = client.OpenRead(remoteFile))
  2299. {
  2300. var actualBytes = new byte[fs.Length];
  2301. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2302. Assert.IsTrue(linesToWriteBytes.IsEqualTo(actualBytes));
  2303. }
  2304. }
  2305. finally
  2306. {
  2307. if (client.Exists(remoteFile))
  2308. {
  2309. client.DeleteFile(remoteFile);
  2310. }
  2311. }
  2312. }
  2313. }
  2314. [TestMethod]
  2315. public void Sftp_WriteAllText_NoEncoding_DirectoryDoesNotExist()
  2316. {
  2317. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2318. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2319. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2320. {
  2321. client.Connect();
  2322. if (client.Exists(remoteFile))
  2323. {
  2324. client.DeleteFile(remoteFile);
  2325. }
  2326. try
  2327. {
  2328. client.WriteAllText(remoteFile, initialContent);
  2329. Assert.Fail();
  2330. }
  2331. catch (SftpPathNotFoundException ex)
  2332. {
  2333. Assert.IsNull(ex.InnerException);
  2334. Assert.AreEqual("No such file", ex.Message);
  2335. }
  2336. finally
  2337. {
  2338. if (client.Exists(remoteFile))
  2339. {
  2340. client.DeleteFile(remoteFile);
  2341. }
  2342. }
  2343. }
  2344. }
  2345. [TestMethod]
  2346. public void Sftp_WriteAllText_NoEncoding_ExistingFile()
  2347. {
  2348. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2349. const string newContent1 = "For\u0116ver & Ever";
  2350. var encoding = new UTF8Encoding(false, true);
  2351. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2352. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2353. var expectedBytes1 = new ArrayBuilder<byte>().Add(newContent1Bytes)
  2354. .Add(initialContentBytes, newContent1Bytes.Length, initialContentBytes.Length - newContent1Bytes.Length)
  2355. .Build();
  2356. var newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2357. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2358. var expectedBytes2 = newContent2Bytes;
  2359. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2360. {
  2361. client.Connect();
  2362. var remoteFile = GenerateUniqueRemoteFileName();
  2363. if (client.Exists(remoteFile))
  2364. {
  2365. client.DeleteFile(remoteFile);
  2366. }
  2367. try
  2368. {
  2369. client.WriteAllText(remoteFile, initialContent);
  2370. #region Write less bytes than the current content, overwriting part of that content
  2371. client.WriteAllText(remoteFile, newContent1);
  2372. using (var fs = client.OpenRead(remoteFile))
  2373. {
  2374. var actualBytes = new byte[fs.Length];
  2375. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2376. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2377. }
  2378. #endregion Write less bytes than the current content, overwriting part of that content
  2379. #region Write more bytes than the current content, overwriting and appending to that content
  2380. client.WriteAllText(remoteFile, newContent2);
  2381. using (var fs = client.OpenRead(remoteFile))
  2382. {
  2383. var actualBytes = new byte[fs.Length];
  2384. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2385. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2386. }
  2387. #endregion Write more bytes than the current content, overwriting and appending to that content
  2388. }
  2389. finally
  2390. {
  2391. if (client.Exists(remoteFile))
  2392. {
  2393. client.DeleteFile(remoteFile);
  2394. }
  2395. }
  2396. }
  2397. }
  2398. [TestMethod]
  2399. public void Sftp_WriteAllText_NoEncoding_FileDoesNotExist()
  2400. {
  2401. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2402. var encoding = new UTF8Encoding(false, true);
  2403. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2404. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2405. {
  2406. client.Connect();
  2407. var remoteFile = GenerateUniqueRemoteFileName();
  2408. if (client.Exists(remoteFile))
  2409. {
  2410. client.DeleteFile(remoteFile);
  2411. }
  2412. try
  2413. {
  2414. client.WriteAllText(remoteFile, initialContent);
  2415. using (var fs = client.OpenRead(remoteFile))
  2416. {
  2417. var actualBytes = new byte[fs.Length];
  2418. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2419. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  2420. }
  2421. }
  2422. finally
  2423. {
  2424. if (client.Exists(remoteFile))
  2425. {
  2426. client.DeleteFile(remoteFile);
  2427. }
  2428. }
  2429. }
  2430. }
  2431. [TestMethod]
  2432. public void Sftp_WriteAllText_Encoding_DirectoryDoesNotExist()
  2433. {
  2434. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2435. var encoding = GetRandomEncoding();
  2436. const string content = "For\u0116ver & Ever";
  2437. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2438. {
  2439. client.Connect();
  2440. if (client.Exists(remoteFile))
  2441. {
  2442. client.DeleteFile(remoteFile);
  2443. }
  2444. try
  2445. {
  2446. client.WriteAllText(remoteFile, content, encoding);
  2447. Assert.Fail();
  2448. }
  2449. catch (SftpPathNotFoundException ex)
  2450. {
  2451. Assert.IsNull(ex.InnerException);
  2452. Assert.AreEqual("No such file", ex.Message);
  2453. }
  2454. finally
  2455. {
  2456. if (client.Exists(remoteFile))
  2457. {
  2458. client.DeleteFile(remoteFile);
  2459. }
  2460. }
  2461. }
  2462. }
  2463. [TestMethod]
  2464. public void Sftp_WriteAllText_Encoding_ExistingFile()
  2465. {
  2466. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2467. const string newContent1 = "For\u0116ver & Ever";
  2468. const string newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2469. var encoding = GetRandomEncoding();
  2470. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2471. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2472. var expectedBytes1 = new ArrayBuilder<byte>().Add(newContent1Bytes)
  2473. .Add(initialContentBytes, newContent1Bytes.Length, initialContentBytes.Length - newContent1Bytes.Length)
  2474. .Build();
  2475. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2476. var expectedBytes2 = newContent2Bytes;
  2477. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2478. {
  2479. client.Connect();
  2480. var remoteFile = GenerateUniqueRemoteFileName();
  2481. if (client.Exists(remoteFile))
  2482. {
  2483. client.DeleteFile(remoteFile);
  2484. }
  2485. try
  2486. {
  2487. client.WriteAllText(remoteFile, initialContent, encoding);
  2488. #region Write less bytes than the current content, overwriting part of that content
  2489. client.WriteAllText(remoteFile, newContent1, encoding);
  2490. using (var fs = client.OpenRead(remoteFile))
  2491. {
  2492. var actualBytes = new byte[fs.Length];
  2493. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2494. Assert.IsTrue(expectedBytes1.IsEqualTo(actualBytes));
  2495. }
  2496. #endregion Write less bytes than the current content, overwriting part of that content
  2497. #region Write more bytes than the current content, overwriting and appending to that content
  2498. client.WriteAllText(remoteFile, newContent2, encoding);
  2499. using (var fs = client.OpenRead(remoteFile))
  2500. {
  2501. var actualBytes = new byte[fs.Length];
  2502. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2503. Assert.IsTrue(expectedBytes2.IsEqualTo(actualBytes));
  2504. }
  2505. #endregion Write more bytes than the current content, overwriting and appending to that content
  2506. }
  2507. finally
  2508. {
  2509. if (client.Exists(remoteFile))
  2510. {
  2511. client.DeleteFile(remoteFile);
  2512. }
  2513. }
  2514. }
  2515. }
  2516. [TestMethod]
  2517. public void Sftp_WriteAllText_Encoding_FileDoesNotExist()
  2518. {
  2519. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2520. var encoding = GetRandomEncoding();
  2521. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2522. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2523. {
  2524. client.Connect();
  2525. var remoteFile = GenerateUniqueRemoteFileName();
  2526. if (client.Exists(remoteFile))
  2527. {
  2528. client.DeleteFile(remoteFile);
  2529. }
  2530. try
  2531. {
  2532. client.WriteAllText(remoteFile, initialContent, encoding);
  2533. using (var fs = client.OpenRead(remoteFile))
  2534. {
  2535. var actualBytes = new byte[fs.Length];
  2536. _ = fs.Read(actualBytes, offset: 0, actualBytes.Length);
  2537. Assert.IsTrue(initialContentBytes.IsEqualTo(actualBytes));
  2538. }
  2539. }
  2540. finally
  2541. {
  2542. if (client.Exists(remoteFile))
  2543. {
  2544. client.DeleteFile(remoteFile);
  2545. }
  2546. }
  2547. }
  2548. }
  2549. [TestMethod]
  2550. public void Sftp_BeginDownloadFile_FileDoesNotExist()
  2551. {
  2552. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2553. {
  2554. client.Connect();
  2555. var remoteFile = GenerateUniqueRemoteFileName();
  2556. if (client.Exists(remoteFile))
  2557. {
  2558. client.DeleteFile(remoteFile);
  2559. }
  2560. try
  2561. {
  2562. using (var ms = new MemoryStream())
  2563. {
  2564. var asyncResult = client.BeginDownloadFile(remoteFile, ms);
  2565. try
  2566. {
  2567. client.EndDownloadFile(asyncResult);
  2568. Assert.Fail();
  2569. }
  2570. catch (SftpPathNotFoundException ex)
  2571. {
  2572. Assert.IsNull(ex.InnerException);
  2573. Assert.AreEqual("No such file", ex.Message);
  2574. // ensure file was not created by us
  2575. Assert.IsFalse(client.Exists(remoteFile));
  2576. }
  2577. }
  2578. }
  2579. finally
  2580. {
  2581. if (client.Exists(remoteFile))
  2582. {
  2583. client.DeleteFile(remoteFile);
  2584. }
  2585. }
  2586. }
  2587. }
  2588. [TestMethod]
  2589. public void Sftp_BeginListDirectory_DirectoryDoesNotExist()
  2590. {
  2591. const string remoteDirectory = "/home/sshnet/test123";
  2592. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2593. {
  2594. client.Connect();
  2595. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2596. {
  2597. command.Execute();
  2598. }
  2599. }
  2600. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2601. {
  2602. client.Connect();
  2603. var asyncResult = client.BeginListDirectory(remoteDirectory, null, null);
  2604. try
  2605. {
  2606. client.EndListDirectory(asyncResult);
  2607. Assert.Fail();
  2608. }
  2609. catch (SftpPathNotFoundException ex)
  2610. {
  2611. Assert.IsNull(ex.InnerException);
  2612. Assert.AreEqual("No such file", ex.Message);
  2613. // ensure directory was not created by us
  2614. Assert.IsFalse(client.Exists(remoteDirectory));
  2615. }
  2616. }
  2617. }
  2618. [TestMethod]
  2619. public void Sftp_BeginUploadFile_InputAndPath_DirectoryDoesNotExist()
  2620. {
  2621. const int size = 50 * 1024 * 1024;
  2622. const string remoteDirectory = "/home/sshnet/test123";
  2623. const string remoteFile = remoteDirectory + "/test";
  2624. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2625. {
  2626. client.Connect();
  2627. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2628. {
  2629. command.Execute();
  2630. }
  2631. }
  2632. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2633. {
  2634. client.Connect();
  2635. var memoryStream = CreateMemoryStream(size);
  2636. memoryStream.Position = 0;
  2637. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile);
  2638. try
  2639. {
  2640. client.EndUploadFile(asyncResult);
  2641. Assert.Fail();
  2642. }
  2643. catch (SftpPathNotFoundException)
  2644. {
  2645. }
  2646. }
  2647. }
  2648. [TestMethod]
  2649. public void Sftp_BeginUploadFile_InputAndPath_FileDoesNotExist()
  2650. {
  2651. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2652. {
  2653. client.Connect();
  2654. var remoteFile = GenerateUniqueRemoteFileName();
  2655. if (client.Exists(remoteFile))
  2656. {
  2657. client.DeleteFile(remoteFile);
  2658. }
  2659. try
  2660. {
  2661. var uploadMemoryStream = new MemoryStream();
  2662. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2663. sw.Write("Gert & Ann");
  2664. sw.Flush();
  2665. uploadMemoryStream.Position = 0;
  2666. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2667. client.EndUploadFile(asyncResult);
  2668. using (var downloadMemoryStream = new MemoryStream())
  2669. {
  2670. client.DownloadFile(remoteFile, downloadMemoryStream);
  2671. downloadMemoryStream.Position = 0;
  2672. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2673. {
  2674. var content = sr.ReadToEnd();
  2675. Assert.AreEqual("Gert & Ann", content);
  2676. }
  2677. }
  2678. }
  2679. finally
  2680. {
  2681. if (client.Exists(remoteFile))
  2682. {
  2683. client.DeleteFile(remoteFile);
  2684. }
  2685. }
  2686. }
  2687. }
  2688. [TestMethod]
  2689. public void Sftp_BeginUploadFile_InputAndPath_ExistingFile()
  2690. {
  2691. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2692. {
  2693. client.Connect();
  2694. var remoteFile = GenerateUniqueRemoteFileName();
  2695. if (client.Exists(remoteFile))
  2696. {
  2697. client.DeleteFile(remoteFile);
  2698. }
  2699. try
  2700. {
  2701. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2702. var uploadMemoryStream = new MemoryStream();
  2703. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2704. sw.Write("Ann & Gert");
  2705. sw.Flush();
  2706. uploadMemoryStream.Position = 0;
  2707. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2708. client.EndUploadFile(asyncResult);
  2709. using (var downloadMemoryStream = new MemoryStream())
  2710. {
  2711. client.DownloadFile(remoteFile, downloadMemoryStream);
  2712. downloadMemoryStream.Position = 0;
  2713. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2714. {
  2715. var content = sr.ReadToEnd();
  2716. Assert.AreEqual("Ann & Gert", content);
  2717. }
  2718. }
  2719. }
  2720. finally
  2721. {
  2722. if (client.Exists(remoteFile))
  2723. {
  2724. client.DeleteFile(remoteFile);
  2725. }
  2726. }
  2727. }
  2728. }
  2729. [TestMethod]
  2730. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_DirectoryDoesNotExist()
  2731. {
  2732. const int size = 50 * 1024 * 1024;
  2733. const string remoteDirectory = "/home/sshnet/test123";
  2734. const string remoteFile = remoteDirectory + "/test";
  2735. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2736. {
  2737. client.Connect();
  2738. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2739. {
  2740. command.Execute();
  2741. }
  2742. }
  2743. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2744. {
  2745. client.Connect();
  2746. var memoryStream = CreateMemoryStream(size);
  2747. memoryStream.Position = 0;
  2748. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, false, null, null);
  2749. try
  2750. {
  2751. client.EndUploadFile(asyncResult);
  2752. Assert.Fail();
  2753. }
  2754. catch (SftpPathNotFoundException)
  2755. {
  2756. }
  2757. }
  2758. }
  2759. [TestMethod]
  2760. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_FileDoesNotExist()
  2761. {
  2762. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2763. {
  2764. client.Connect();
  2765. var remoteFile = GenerateUniqueRemoteFileName();
  2766. if (client.Exists(remoteFile))
  2767. {
  2768. client.DeleteFile(remoteFile);
  2769. }
  2770. try
  2771. {
  2772. using (var uploadMemoryStream = new MemoryStream())
  2773. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2774. {
  2775. sw.Write("Gert & Ann");
  2776. sw.Flush();
  2777. uploadMemoryStream.Position = 0;
  2778. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2779. client.EndUploadFile(asyncResult);
  2780. }
  2781. using (var downloadMemoryStream = new MemoryStream())
  2782. {
  2783. client.DownloadFile(remoteFile, downloadMemoryStream);
  2784. downloadMemoryStream.Position = 0;
  2785. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2786. {
  2787. var content = sr.ReadToEnd();
  2788. Assert.AreEqual("Gert & Ann", content);
  2789. }
  2790. }
  2791. }
  2792. finally
  2793. {
  2794. if (client.Exists(remoteFile))
  2795. {
  2796. client.DeleteFile(remoteFile);
  2797. }
  2798. }
  2799. }
  2800. }
  2801. [TestMethod]
  2802. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_ExistingFile()
  2803. {
  2804. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2805. {
  2806. client.Connect();
  2807. var remoteFile = GenerateUniqueRemoteFileName();
  2808. if (client.Exists(remoteFile))
  2809. {
  2810. client.DeleteFile(remoteFile);
  2811. }
  2812. try
  2813. {
  2814. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2815. var uploadMemoryStream = new MemoryStream();
  2816. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2817. sw.Write("Ann & Gert");
  2818. sw.Flush();
  2819. uploadMemoryStream.Position = 0;
  2820. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2821. try
  2822. {
  2823. client.EndUploadFile(asyncResult);
  2824. Assert.Fail();
  2825. }
  2826. catch (SshException ex)
  2827. {
  2828. Assert.AreEqual(typeof(SshException), ex.GetType());
  2829. Assert.IsNull(ex.InnerException);
  2830. Assert.AreEqual("Failure", ex.Message);
  2831. }
  2832. }
  2833. finally
  2834. {
  2835. if (client.Exists(remoteFile))
  2836. {
  2837. client.DeleteFile(remoteFile);
  2838. }
  2839. }
  2840. }
  2841. }
  2842. [TestMethod]
  2843. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_DirectoryDoesNotExist()
  2844. {
  2845. const int size = 50 * 1024 * 1024;
  2846. const string remoteDirectory = "/home/sshnet/test123";
  2847. const string remoteFile = remoteDirectory + "/test";
  2848. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2849. {
  2850. client.Connect();
  2851. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2852. {
  2853. command.Execute();
  2854. }
  2855. }
  2856. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2857. {
  2858. client.Connect();
  2859. var memoryStream = CreateMemoryStream(size);
  2860. memoryStream.Position = 0;
  2861. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, true, null, null);
  2862. try
  2863. {
  2864. client.EndUploadFile(asyncResult);
  2865. Assert.Fail();
  2866. }
  2867. catch (SftpPathNotFoundException)
  2868. {
  2869. }
  2870. }
  2871. }
  2872. [TestMethod]
  2873. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_FileDoesNotExist()
  2874. {
  2875. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2876. {
  2877. client.Connect();
  2878. var remoteFile = GenerateUniqueRemoteFileName();
  2879. if (client.Exists(remoteFile))
  2880. {
  2881. client.DeleteFile(remoteFile);
  2882. }
  2883. try
  2884. {
  2885. using (var uploadMemoryStream = new MemoryStream())
  2886. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2887. {
  2888. sw.Write("Gert & Ann");
  2889. sw.Flush();
  2890. uploadMemoryStream.Position = 0;
  2891. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2892. client.EndUploadFile(asyncResult);
  2893. }
  2894. using (var downloadMemoryStream = new MemoryStream())
  2895. {
  2896. client.DownloadFile(remoteFile, downloadMemoryStream);
  2897. downloadMemoryStream.Position = 0;
  2898. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2899. {
  2900. var content = sr.ReadToEnd();
  2901. Assert.AreEqual("Gert & Ann", content);
  2902. }
  2903. }
  2904. }
  2905. finally
  2906. {
  2907. if (client.Exists(remoteFile))
  2908. {
  2909. client.DeleteFile(remoteFile);
  2910. }
  2911. }
  2912. }
  2913. }
  2914. [TestMethod]
  2915. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_ExistingFile()
  2916. {
  2917. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2918. {
  2919. client.Connect();
  2920. var remoteFile = GenerateUniqueRemoteFileName();
  2921. if (client.Exists(remoteFile))
  2922. {
  2923. client.DeleteFile(remoteFile);
  2924. }
  2925. try
  2926. {
  2927. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2928. using (var uploadMemoryStream = new MemoryStream())
  2929. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2930. {
  2931. sw.Write("Ann & Gert");
  2932. sw.Flush();
  2933. uploadMemoryStream.Position = 0;
  2934. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2935. client.EndUploadFile(asyncResult);
  2936. }
  2937. using (var downloadMemoryStream = new MemoryStream())
  2938. {
  2939. client.DownloadFile(remoteFile, downloadMemoryStream);
  2940. downloadMemoryStream.Position = 0;
  2941. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2942. {
  2943. var content = sr.ReadToEnd();
  2944. Assert.AreEqual("Ann & Gert", content);
  2945. }
  2946. }
  2947. }
  2948. finally
  2949. {
  2950. if (client.Exists(remoteFile))
  2951. {
  2952. client.DeleteFile(remoteFile);
  2953. }
  2954. }
  2955. }
  2956. }
  2957. [TestMethod]
  2958. public void Sftp_UploadAndDownloadBigFile()
  2959. {
  2960. const int size = 50 * 1024 * 1024;
  2961. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2962. {
  2963. client.Connect();
  2964. var remoteFile = GenerateUniqueRemoteFileName();
  2965. if (client.Exists(remoteFile))
  2966. {
  2967. client.Delete(remoteFile);
  2968. }
  2969. try
  2970. {
  2971. var memoryStream = CreateMemoryStream(size);
  2972. memoryStream.Position = 0;
  2973. client.UploadFile(memoryStream, remoteFile);
  2974. var stopwatch = new Stopwatch();
  2975. stopwatch.Start();
  2976. // check uploaded file
  2977. memoryStream = new MemoryStream();
  2978. client.DownloadFile(remoteFile, memoryStream);
  2979. Assert.AreEqual(size, memoryStream.Length);
  2980. stopwatch.Stop();
  2981. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  2982. Console.WriteLine(@"Transfer speed: {0:N2} KB/s",
  2983. CalculateTransferSpeed(memoryStream.Length, stopwatch.ElapsedMilliseconds));
  2984. }
  2985. finally
  2986. {
  2987. if (client.Exists(remoteFile))
  2988. {
  2989. client.Delete(remoteFile);
  2990. }
  2991. }
  2992. }
  2993. }
  2994. /// <summary>
  2995. /// Issue 1672
  2996. /// </summary>
  2997. [TestMethod]
  2998. public void Sftp_CurrentWorkingDirectory()
  2999. {
  3000. const string homeDirectory = "/home/sshnet";
  3001. const string otherDirectory = homeDirectory + "/dir";
  3002. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3003. {
  3004. client.Connect();
  3005. if (client.Exists(otherDirectory))
  3006. {
  3007. client.DeleteDirectory(otherDirectory);
  3008. }
  3009. try
  3010. {
  3011. client.CreateDirectory(otherDirectory);
  3012. client.ChangeDirectory(otherDirectory);
  3013. using (var s = CreateStreamWithContent("A"))
  3014. {
  3015. client.UploadFile(s, "a.txt");
  3016. }
  3017. using (var s = new MemoryStream())
  3018. {
  3019. client.DownloadFile("a.txt", s);
  3020. s.Position = 0;
  3021. var content = Encoding.ASCII.GetString(s.ToArray());
  3022. Assert.AreEqual("A", content);
  3023. }
  3024. Assert.IsTrue(client.Exists(otherDirectory + "/a.txt"));
  3025. client.DeleteFile("a.txt");
  3026. Assert.IsFalse(client.Exists(otherDirectory + "/a.txt"));
  3027. client.DeleteDirectory(".");
  3028. Assert.IsFalse(client.Exists(otherDirectory));
  3029. }
  3030. finally
  3031. {
  3032. if (client.Exists(otherDirectory))
  3033. {
  3034. client.DeleteDirectory(otherDirectory);
  3035. }
  3036. }
  3037. }
  3038. }
  3039. [TestMethod]
  3040. public void Sftp_Exists()
  3041. {
  3042. const string remoteHome = "/home/sshnet";
  3043. #region Setup
  3044. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3045. {
  3046. client.Connect();
  3047. #region Clean-up
  3048. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3049. {
  3050. command.Execute();
  3051. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3052. }
  3053. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3054. {
  3055. command.Execute();
  3056. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3057. }
  3058. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  3059. )
  3060. {
  3061. command.Execute();
  3062. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3063. }
  3064. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3065. {
  3066. command.Execute();
  3067. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3068. }
  3069. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3070. {
  3071. command.Execute();
  3072. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3073. }
  3074. #endregion Clean-up
  3075. #region Setup
  3076. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  3077. {
  3078. command.Execute();
  3079. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3080. }
  3081. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  3082. {
  3083. command.Execute();
  3084. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3085. }
  3086. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  3087. {
  3088. command.Execute();
  3089. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3090. }
  3091. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  3092. {
  3093. command.Execute();
  3094. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3095. }
  3096. #endregion Setup
  3097. }
  3098. #endregion Setup
  3099. #region Assert
  3100. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3101. {
  3102. client.Connect();
  3103. Assert.IsFalse(client.Exists(remoteHome + "/DoesNotExist"));
  3104. Assert.IsTrue(client.Exists(remoteHome + "/file.exists"));
  3105. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.file.exists"));
  3106. Assert.IsTrue(client.Exists(remoteHome + "/directory.exists"));
  3107. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.directory.exists"));
  3108. }
  3109. #endregion Assert
  3110. #region Teardown
  3111. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3112. {
  3113. client.Connect();
  3114. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3115. {
  3116. command.Execute();
  3117. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3118. }
  3119. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3120. {
  3121. command.Execute();
  3122. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3123. }
  3124. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  3125. {
  3126. command.Execute();
  3127. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3128. }
  3129. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3130. {
  3131. command.Execute();
  3132. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3133. }
  3134. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3135. {
  3136. command.Execute();
  3137. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3138. }
  3139. }
  3140. #endregion Teardown
  3141. }
  3142. [TestMethod]
  3143. public async Task Sftp_ExistsAsync()
  3144. {
  3145. const string remoteHome = "/home/sshnet";
  3146. #region Setup
  3147. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3148. {
  3149. client.Connect();
  3150. #region Clean-up
  3151. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3152. {
  3153. await command.ExecuteAsync();
  3154. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3155. }
  3156. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3157. {
  3158. await command.ExecuteAsync();
  3159. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3160. }
  3161. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  3162. )
  3163. {
  3164. await command.ExecuteAsync();
  3165. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3166. }
  3167. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3168. {
  3169. await command.ExecuteAsync();
  3170. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3171. }
  3172. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3173. {
  3174. await command.ExecuteAsync();
  3175. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3176. }
  3177. #endregion Clean-up
  3178. #region Setup
  3179. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  3180. {
  3181. await command.ExecuteAsync();
  3182. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3183. }
  3184. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  3185. {
  3186. await command.ExecuteAsync();
  3187. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3188. }
  3189. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  3190. {
  3191. await command.ExecuteAsync();
  3192. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3193. }
  3194. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  3195. {
  3196. await command.ExecuteAsync();
  3197. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3198. }
  3199. #endregion Setup
  3200. }
  3201. #endregion Setup
  3202. #region Assert
  3203. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3204. {
  3205. await client.ConnectAsync(default).ConfigureAwait(false);
  3206. Assert.IsFalse(await client.ExistsAsync(remoteHome + "/DoesNotExist"));
  3207. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/file.exists"));
  3208. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/symlink.to.file.exists"));
  3209. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/directory.exists"));
  3210. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/symlink.to.directory.exists"));
  3211. }
  3212. #endregion Assert
  3213. #region Teardown
  3214. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3215. {
  3216. client.Connect();
  3217. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  3218. {
  3219. await command.ExecuteAsync();
  3220. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3221. }
  3222. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  3223. {
  3224. await command.ExecuteAsync();
  3225. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3226. }
  3227. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  3228. {
  3229. await command.ExecuteAsync();
  3230. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3231. }
  3232. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  3233. {
  3234. await command.ExecuteAsync();
  3235. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3236. }
  3237. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  3238. {
  3239. await command.ExecuteAsync();
  3240. Assert.AreEqual(0, command.ExitStatus, command.Error);
  3241. }
  3242. }
  3243. #endregion Teardown
  3244. }
  3245. [TestMethod]
  3246. public void Sftp_ListDirectory()
  3247. {
  3248. const string remoteDirectory = "/home/sshnet/test123";
  3249. try
  3250. {
  3251. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3252. {
  3253. client.Connect();
  3254. client.RunCommand($@"rm -Rf ""{remoteDirectory}""");
  3255. client.RunCommand($@"mkdir -p ""{remoteDirectory}""");
  3256. client.RunCommand($@"mkdir -p ""{remoteDirectory}/sub""");
  3257. client.RunCommand($@"touch ""{remoteDirectory}/file1""");
  3258. client.RunCommand($@"touch ""{remoteDirectory}/file2""");
  3259. }
  3260. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3261. {
  3262. client.Connect();
  3263. client.ChangeDirectory(remoteDirectory);
  3264. var directoryContent = client.ListDirectory(".").OrderBy(p => p.Name).ToList();
  3265. Assert.AreEqual(5, directoryContent.Count);
  3266. Assert.AreEqual(".", directoryContent[0].Name);
  3267. Assert.AreEqual($"{remoteDirectory}/.", directoryContent[0].FullName);
  3268. Assert.IsTrue(directoryContent[0].IsDirectory);
  3269. Assert.AreEqual("..", directoryContent[1].Name);
  3270. Assert.AreEqual($"{remoteDirectory}/..", directoryContent[1].FullName);
  3271. Assert.IsTrue(directoryContent[1].IsDirectory);
  3272. Assert.AreEqual("file1", directoryContent[2].Name);
  3273. Assert.AreEqual($"{remoteDirectory}/file1", directoryContent[2].FullName);
  3274. Assert.IsFalse(directoryContent[2].IsDirectory);
  3275. Assert.AreEqual("file2", directoryContent[3].Name);
  3276. Assert.AreEqual($"{remoteDirectory}/file2", directoryContent[3].FullName);
  3277. Assert.IsFalse(directoryContent[3].IsDirectory);
  3278. Assert.AreEqual("sub", directoryContent[4].Name);
  3279. Assert.AreEqual($"{remoteDirectory}/sub", directoryContent[4].FullName);
  3280. Assert.IsTrue(directoryContent[4].IsDirectory);
  3281. }
  3282. }
  3283. finally
  3284. {
  3285. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3286. {
  3287. client.Connect();
  3288. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3289. {
  3290. command.Execute();
  3291. }
  3292. }
  3293. }
  3294. }
  3295. [TestMethod]
  3296. public void Sftp_ChangeDirectory_DirectoryDoesNotExist()
  3297. {
  3298. const string remoteDirectory = "/home/sshnet/test123";
  3299. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3300. {
  3301. client.Connect();
  3302. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3303. {
  3304. command.Execute();
  3305. }
  3306. }
  3307. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3308. {
  3309. client.Connect();
  3310. try
  3311. {
  3312. client.ChangeDirectory(remoteDirectory);
  3313. Assert.Fail();
  3314. }
  3315. catch (SftpPathNotFoundException)
  3316. {
  3317. }
  3318. }
  3319. }
  3320. [TestMethod]
  3321. public async Task Sftp_ChangeDirectory_DirectoryDoesNotExistAsync()
  3322. {
  3323. const string remoteDirectory = "/home/sshnet/test123";
  3324. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3325. {
  3326. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3327. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3328. {
  3329. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3330. }
  3331. }
  3332. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3333. {
  3334. client.Connect();
  3335. try
  3336. {
  3337. await client.ChangeDirectoryAsync(remoteDirectory, CancellationToken.None).ConfigureAwait(false);
  3338. Assert.Fail();
  3339. }
  3340. catch (SftpPathNotFoundException)
  3341. {
  3342. }
  3343. }
  3344. }
  3345. [TestMethod]
  3346. public void Sftp_ChangeDirectory_DirectoryExists()
  3347. {
  3348. const string remoteDirectory = "/home/sshnet/test123";
  3349. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3350. {
  3351. client.Connect();
  3352. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3353. {
  3354. command.Execute();
  3355. }
  3356. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3357. {
  3358. command.Execute();
  3359. }
  3360. }
  3361. try
  3362. {
  3363. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3364. {
  3365. client.Connect();
  3366. client.ChangeDirectory(remoteDirectory);
  3367. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3368. using (var uploadStream = CreateMemoryStream(100))
  3369. {
  3370. uploadStream.Position = 0;
  3371. client.UploadFile(uploadStream, "gert.txt");
  3372. uploadStream.Position = 0;
  3373. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3374. {
  3375. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3376. }
  3377. }
  3378. }
  3379. }
  3380. finally
  3381. {
  3382. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3383. {
  3384. client.Connect();
  3385. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3386. {
  3387. command.Execute();
  3388. }
  3389. }
  3390. }
  3391. }
  3392. [TestMethod]
  3393. public async Task Sftp_ChangeDirectory_DirectoryExistsAsync()
  3394. {
  3395. const string remoteDirectory = "/home/sshnet/test123";
  3396. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3397. {
  3398. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3399. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3400. {
  3401. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3402. }
  3403. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3404. {
  3405. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3406. }
  3407. }
  3408. try
  3409. {
  3410. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3411. {
  3412. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3413. await client.ChangeDirectoryAsync(remoteDirectory, CancellationToken.None).ConfigureAwait(false);
  3414. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3415. using (var uploadStream = CreateMemoryStream(100))
  3416. {
  3417. uploadStream.Position = 0;
  3418. await client.UploadFileAsync(uploadStream, "gert.txt").ConfigureAwait(false);
  3419. uploadStream.Position = 0;
  3420. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3421. {
  3422. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3423. }
  3424. }
  3425. }
  3426. }
  3427. finally
  3428. {
  3429. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3430. {
  3431. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3432. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3433. {
  3434. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3435. }
  3436. }
  3437. }
  3438. }
  3439. [TestMethod]
  3440. public void Sftp_DownloadFile_MemoryStream()
  3441. {
  3442. const int fileSize = 500 * 1024;
  3443. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3444. {
  3445. client.Connect();
  3446. var remoteFile = GenerateUniqueRemoteFileName();
  3447. SftpCreateRemoteFile(client, remoteFile, fileSize);
  3448. try
  3449. {
  3450. using (var memoryStream = new MemoryStream())
  3451. {
  3452. var stopwatch = new Stopwatch();
  3453. stopwatch.Start();
  3454. client.DownloadFile(remoteFile, memoryStream);
  3455. stopwatch.Stop();
  3456. var transferSpeed = CalculateTransferSpeed(memoryStream.Length, stopwatch.ElapsedMilliseconds);
  3457. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  3458. Console.WriteLine(@"Transfer speed: {0:N2} KB/s", transferSpeed);
  3459. Assert.AreEqual(fileSize, memoryStream.Length);
  3460. }
  3461. }
  3462. finally
  3463. {
  3464. if (client.Exists(remoteFile))
  3465. {
  3466. client.DeleteFile(remoteFile);
  3467. }
  3468. }
  3469. }
  3470. }
  3471. [TestMethod]
  3472. public void Sftp_SubsystemExecution_Failed()
  3473. {
  3474. var remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
  3475. // Disable SFTP subsystem
  3476. remoteSshdConfig.ClearSubsystems()
  3477. .Update()
  3478. .Restart();
  3479. var remoteSshdReconfiguredToDefaultState = false;
  3480. try
  3481. {
  3482. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3483. {
  3484. try
  3485. {
  3486. client.Connect();
  3487. Assert.Fail("Establishing SFTP connection should have failed.");
  3488. }
  3489. catch (SshException ex)
  3490. {
  3491. Assert.IsNull(ex.InnerException);
  3492. Assert.AreEqual("Subsystem 'sftp' could not be executed.", ex.Message);
  3493. }
  3494. // Re-enable SFTP subsystem
  3495. remoteSshdConfig.Reset();
  3496. remoteSshdReconfiguredToDefaultState = true;
  3497. // ensure we can reconnect the same SftpClient instance
  3498. client.Connect();
  3499. // ensure SFTP session is correctly established
  3500. Assert.IsTrue(client.Exists("."));
  3501. }
  3502. }
  3503. finally
  3504. {
  3505. if (!remoteSshdReconfiguredToDefaultState)
  3506. {
  3507. remoteSshdConfig.Reset();
  3508. }
  3509. }
  3510. }
  3511. [TestMethod]
  3512. public void Sftp_SftpFileStream_ReadAndWrite()
  3513. {
  3514. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3515. {
  3516. client.Connect();
  3517. var remoteFile = GenerateUniqueRemoteFileName();
  3518. if (client.Exists(remoteFile))
  3519. {
  3520. client.DeleteFile(remoteFile);
  3521. }
  3522. try
  3523. {
  3524. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3525. {
  3526. s.Write(new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3527. }
  3528. // switch from read to write mode
  3529. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3530. {
  3531. Assert.AreEqual(4, s.ReadByte());
  3532. Assert.AreEqual(3, s.ReadByte());
  3533. Assert.AreEqual(2, s.Position);
  3534. s.WriteByte(7);
  3535. s.Write(new byte[] { 8, 9, 10, 11, 12 }, 1, 3);
  3536. Assert.AreEqual(6, s.Position);
  3537. }
  3538. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3539. {
  3540. Assert.AreEqual(6, s.Length);
  3541. var buffer = new byte[s.Length];
  3542. Assert.AreEqual(6, s.Read(buffer, offset: 0, buffer.Length));
  3543. CollectionAssert.AreEqual(new byte[] { 4, 3, 7, 9, 10, 11 }, buffer);
  3544. // Ensure we've reached end of the stream
  3545. Assert.AreEqual(-1, s.ReadByte());
  3546. }
  3547. // switch from read to write mode, and back to read mode and finally
  3548. // append a byte
  3549. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3550. {
  3551. Assert.AreEqual(4, s.ReadByte());
  3552. Assert.AreEqual(3, s.ReadByte());
  3553. Assert.AreEqual(7, s.ReadByte());
  3554. s.Write(new byte[] { 0, 1, 6, 4 }, 1, 2);
  3555. Assert.AreEqual(11, s.ReadByte());
  3556. // Ensure we've reached end of the stream
  3557. Assert.AreEqual(-1, s.ReadByte());
  3558. s.WriteByte(12);
  3559. }
  3560. // switch from write to read mode, and back to write mode
  3561. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3562. {
  3563. s.WriteByte(5);
  3564. Assert.AreEqual(3, s.ReadByte());
  3565. s.WriteByte(13);
  3566. Assert.AreEqual(3, s.Position);
  3567. }
  3568. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3569. {
  3570. Assert.AreEqual(7, s.Length);
  3571. var buffer = new byte[s.Length];
  3572. Assert.AreEqual(7, s.Read(buffer, offset: 0, buffer.Length));
  3573. CollectionAssert.AreEqual(new byte[] { 5, 3, 13, 1, 6, 11, 12 }, buffer);
  3574. // Ensure we've reached end of the stream
  3575. Assert.AreEqual(-1, s.ReadByte());
  3576. }
  3577. }
  3578. finally
  3579. {
  3580. if (client.Exists(remoteFile))
  3581. {
  3582. client.DeleteFile(remoteFile);
  3583. }
  3584. }
  3585. }
  3586. }
  3587. [TestMethod]
  3588. public void Sftp_SftpFileStream_SetLength_ReduceLength()
  3589. {
  3590. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3591. {
  3592. client.Connect();
  3593. var remoteFile = GenerateUniqueRemoteFileName();
  3594. if (client.Exists(remoteFile))
  3595. {
  3596. client.DeleteFile(remoteFile);
  3597. }
  3598. try
  3599. {
  3600. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3601. {
  3602. s.Write(new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3603. }
  3604. // reduce length while in write mode, with data in write buffer, and before
  3605. // current position
  3606. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  3607. {
  3608. s.Position = 3;
  3609. s.Write(new byte[] { 6, 7, 8, 9 }, offset: 0, count: 4);
  3610. Assert.AreEqual(7, s.Position);
  3611. // verify buffer has not yet been flushed
  3612. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3613. {
  3614. Assert.AreEqual(4, fs.ReadByte());
  3615. Assert.AreEqual(3, fs.ReadByte());
  3616. Assert.AreEqual(2, fs.ReadByte());
  3617. // Ensure we've reached end of the stream
  3618. Assert.AreEqual(-1, fs.ReadByte());
  3619. }
  3620. s.SetLength(5);
  3621. Assert.AreEqual(5, s.Position);
  3622. // verify that buffer was flushed and size has been modified
  3623. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3624. {
  3625. Assert.AreEqual(4, fs.ReadByte());
  3626. Assert.AreEqual(3, fs.ReadByte());
  3627. Assert.AreEqual(2, fs.ReadByte());
  3628. Assert.AreEqual(6, fs.ReadByte());
  3629. Assert.AreEqual(7, fs.ReadByte());
  3630. // Ensure we've reached end of the stream
  3631. Assert.AreEqual(-1, fs.ReadByte());
  3632. }
  3633. s.WriteByte(1);
  3634. }
  3635. // verify that last byte was correctly written to the file
  3636. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3637. {
  3638. Assert.AreEqual(6, s.Length);
  3639. var buffer = new byte[s.Length + 2];
  3640. Assert.AreEqual(6, s.Read(buffer, offset: 0, buffer.Length));
  3641. CollectionAssert.AreEqual(new byte[] { 4, 3, 2, 6, 7, 1, 0, 0 }, buffer);
  3642. // Ensure we've reached end of the stream
  3643. Assert.AreEqual(-1, s.ReadByte());
  3644. }
  3645. // reduce length while in read mode, but beyond current position
  3646. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3647. {
  3648. var buffer = new byte[1];
  3649. Assert.AreEqual(1, s.Read(buffer, offset: 0, buffer.Length));
  3650. CollectionAssert.AreEqual(new byte[] { 4 }, buffer);
  3651. s.SetLength(3);
  3652. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  3653. {
  3654. w.Write(new byte[] { 8, 1, 6, 2 }, offset: 0, count: 4);
  3655. }
  3656. // verify that position was not changed
  3657. Assert.AreEqual(1, s.Position);
  3658. // verify that read buffer was cleared
  3659. Assert.AreEqual(1, s.ReadByte());
  3660. Assert.AreEqual(6, s.ReadByte());
  3661. Assert.AreEqual(2, s.ReadByte());
  3662. // Ensure we've reached end of the stream
  3663. Assert.AreEqual(-1, s.ReadByte());
  3664. Assert.AreEqual(4, s.Length);
  3665. }
  3666. // reduce length while in read mode, but before current position
  3667. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3668. {
  3669. var buffer = new byte[4];
  3670. Assert.AreEqual(4, s.Read(buffer, offset: 0, buffer.Length));
  3671. CollectionAssert.AreEqual(new byte[] { 8, 1, 6, 2 }, buffer);
  3672. Assert.AreEqual(4, s.Position);
  3673. s.SetLength(3);
  3674. // verify that position was moved to last byte
  3675. Assert.AreEqual(3, s.Position);
  3676. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3677. {
  3678. Assert.AreEqual(3, w.Length);
  3679. Assert.AreEqual(8, w.ReadByte());
  3680. Assert.AreEqual(1, w.ReadByte());
  3681. Assert.AreEqual(6, w.ReadByte());
  3682. // Ensure we've reached end of the stream
  3683. Assert.AreEqual(-1, w.ReadByte());
  3684. }
  3685. // Ensure we've reached end of the stream
  3686. Assert.AreEqual(-1, s.ReadByte());
  3687. }
  3688. }
  3689. finally
  3690. {
  3691. if (client.Exists(remoteFile))
  3692. {
  3693. client.DeleteFile(remoteFile);
  3694. }
  3695. }
  3696. }
  3697. }
  3698. [TestMethod]
  3699. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginBegin()
  3700. {
  3701. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3702. {
  3703. client.BufferSize = 500;
  3704. client.Connect();
  3705. var remoteFile = GenerateUniqueRemoteFileName();
  3706. if (client.Exists(remoteFile))
  3707. {
  3708. client.DeleteFile(remoteFile);
  3709. }
  3710. try
  3711. {
  3712. // create single-byte file
  3713. using (var fs = client.OpenWrite(remoteFile))
  3714. {
  3715. fs.WriteByte(0x04);
  3716. }
  3717. // seek beyond EOF but not beyond buffer size
  3718. // do not write anything
  3719. using (var fs = client.OpenWrite(remoteFile))
  3720. {
  3721. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3722. Assert.AreEqual(3, newPosition);
  3723. Assert.AreEqual(3, fs.Position);
  3724. }
  3725. using (var fs = client.OpenRead(remoteFile))
  3726. {
  3727. Assert.AreEqual(1, fs.Length);
  3728. Assert.AreEqual(0x04, fs.ReadByte());
  3729. // Ensure we've reached end of the stream
  3730. Assert.AreEqual(-1, fs.ReadByte());
  3731. }
  3732. client.DeleteFile(remoteFile);
  3733. // create single-byte file
  3734. using (var fs = client.OpenWrite(remoteFile))
  3735. {
  3736. fs.WriteByte(0x04);
  3737. }
  3738. // seek beyond EOF and beyond buffer size
  3739. // do not write anything
  3740. using (var fs = client.OpenWrite(remoteFile))
  3741. {
  3742. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  3743. Assert.AreEqual(700, newPosition);
  3744. Assert.AreEqual(700, fs.Position);
  3745. }
  3746. using (var fs = client.OpenRead(remoteFile))
  3747. {
  3748. Assert.AreEqual(1, fs.Length);
  3749. Assert.AreEqual(0x04, fs.ReadByte());
  3750. // Ensure we've reached end of the stream
  3751. Assert.AreEqual(-1, fs.ReadByte());
  3752. }
  3753. client.DeleteFile(remoteFile);
  3754. // create single-byte file
  3755. using (var fs = client.OpenWrite(remoteFile))
  3756. {
  3757. fs.WriteByte(0x04);
  3758. }
  3759. // seek beyond EOF but not beyond buffer size
  3760. // write less bytes than buffer size
  3761. var seekOffset = 3L;
  3762. // buffer holding the data that we'll write to the file
  3763. var writeBuffer = GenerateRandom(size: 7);
  3764. using (var fs = client.OpenWrite(remoteFile))
  3765. {
  3766. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3767. Assert.AreEqual(seekOffset, newPosition);
  3768. Assert.AreEqual(seekOffset, fs.Position);
  3769. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3770. }
  3771. using (var fs = client.OpenRead(remoteFile))
  3772. {
  3773. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3774. Assert.AreEqual(0x04, fs.ReadByte());
  3775. var soughtOverReadBuffer = new byte[seekOffset - 1];
  3776. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3777. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3778. var readBuffer = new byte[writeBuffer.Length];
  3779. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3780. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3781. // Ensure we've reached end of the stream
  3782. Assert.AreEqual(-1, fs.ReadByte());
  3783. }
  3784. client.DeleteFile(remoteFile);
  3785. // create single-byte file
  3786. using (var fs = client.OpenWrite(remoteFile))
  3787. {
  3788. fs.WriteByte(0x04);
  3789. }
  3790. // seek beyond EOF and beyond buffer size
  3791. // write less bytes than buffer size
  3792. seekOffset = 700L;
  3793. // buffer holding the data that we'll write to the file
  3794. writeBuffer = GenerateRandom(size: 4);
  3795. using (var fs = client.OpenWrite(remoteFile))
  3796. {
  3797. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3798. Assert.AreEqual(seekOffset, newPosition);
  3799. Assert.AreEqual(seekOffset, fs.Position);
  3800. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3801. }
  3802. using (var fs = client.OpenRead(remoteFile))
  3803. {
  3804. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3805. Assert.AreEqual(0x04, fs.ReadByte());
  3806. var soughtOverReadBuffer = new byte[seekOffset - 1];
  3807. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3808. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3809. var readBuffer = new byte[writeBuffer.Length];
  3810. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3811. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3812. // Ensure we've reached end of the stream
  3813. Assert.AreEqual(-1, fs.ReadByte());
  3814. }
  3815. client.DeleteFile(remoteFile);
  3816. // create single-byte file
  3817. using (var fs = client.OpenWrite(remoteFile))
  3818. {
  3819. fs.WriteByte(0x04);
  3820. }
  3821. // seek beyond EOF but not beyond buffer size
  3822. // write more bytes than buffer size
  3823. writeBuffer = GenerateRandom(size: 600);
  3824. using (var fs = client.OpenWrite(remoteFile))
  3825. {
  3826. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3827. Assert.AreEqual(3, newPosition);
  3828. Assert.AreEqual(3, fs.Position);
  3829. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3830. }
  3831. using (var fs = client.OpenRead(remoteFile))
  3832. {
  3833. Assert.AreEqual(3 + writeBuffer.Length, fs.Length);
  3834. Assert.AreEqual(0x04, fs.ReadByte());
  3835. Assert.AreEqual(0x00, fs.ReadByte());
  3836. Assert.AreEqual(0x00, fs.ReadByte());
  3837. var readBuffer = new byte[writeBuffer.Length];
  3838. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3839. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3840. // Ensure we've reached end of the stream
  3841. Assert.AreEqual(-1, fs.ReadByte());
  3842. }
  3843. client.DeleteFile(remoteFile);
  3844. // create single-byte file
  3845. using (var fs = client.OpenWrite(remoteFile))
  3846. {
  3847. fs.WriteByte(0x04);
  3848. }
  3849. // seek beyond EOF and beyond buffer size
  3850. // write more bytes than buffer size
  3851. writeBuffer = GenerateRandom(size: 600);
  3852. using (var fs = client.OpenWrite(remoteFile))
  3853. {
  3854. var newPosition = fs.Seek(offset: 550, SeekOrigin.Begin);
  3855. Assert.AreEqual(550, newPosition);
  3856. Assert.AreEqual(550, fs.Position);
  3857. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3858. }
  3859. using (var fs = client.OpenRead(remoteFile))
  3860. {
  3861. Assert.AreEqual(550 + writeBuffer.Length, fs.Length);
  3862. Assert.AreEqual(0x04, fs.ReadByte());
  3863. var soughtOverReadBuffer = new byte[550 - 1];
  3864. Assert.AreEqual(550 - 1, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3865. Assert.IsTrue(new byte[550 - 1].IsEqualTo(soughtOverReadBuffer));
  3866. var readBuffer = new byte[writeBuffer.Length];
  3867. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3868. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3869. // Ensure we've reached end of the stream
  3870. Assert.AreEqual(-1, fs.ReadByte());
  3871. }
  3872. }
  3873. finally
  3874. {
  3875. if (client.Exists(remoteFile))
  3876. {
  3877. client.DeleteFile(remoteFile);
  3878. }
  3879. }
  3880. }
  3881. }
  3882. [TestMethod]
  3883. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginEnd()
  3884. {
  3885. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3886. {
  3887. client.BufferSize = 500;
  3888. client.Connect();
  3889. var remoteFile = GenerateUniqueRemoteFileName();
  3890. if (client.Exists(remoteFile))
  3891. {
  3892. client.DeleteFile(remoteFile);
  3893. }
  3894. try
  3895. {
  3896. // create single-byte file
  3897. using (var fs = client.OpenWrite(remoteFile))
  3898. {
  3899. fs.WriteByte(0x04);
  3900. }
  3901. // seek beyond EOF but not beyond buffer size
  3902. // do not write anything
  3903. using (var fs = client.OpenWrite(remoteFile))
  3904. {
  3905. var newPosition = fs.Seek(offset: 3L, SeekOrigin.End);
  3906. Assert.AreEqual(4, newPosition);
  3907. Assert.AreEqual(4, fs.Position);
  3908. }
  3909. using (var fs = client.OpenRead(remoteFile))
  3910. {
  3911. Assert.AreEqual(1, fs.Length);
  3912. Assert.AreEqual(0x04, fs.ReadByte());
  3913. // Ensure we've reached end of the stream
  3914. Assert.AreEqual(-1, fs.ReadByte());
  3915. }
  3916. client.DeleteFile(remoteFile);
  3917. // create single-byte file
  3918. using (var fs = client.OpenWrite(remoteFile))
  3919. {
  3920. fs.WriteByte(0x04);
  3921. }
  3922. // seek beyond EOF and beyond buffer size
  3923. // do not write anything
  3924. using (var fs = client.OpenWrite(remoteFile))
  3925. {
  3926. var newPosition = fs.Seek(offset: 700L, SeekOrigin.End);
  3927. Assert.AreEqual(701, newPosition);
  3928. Assert.AreEqual(701, fs.Position);
  3929. }
  3930. using (var fs = client.OpenRead(remoteFile))
  3931. {
  3932. Assert.AreEqual(1, fs.Length);
  3933. Assert.AreEqual(0x04, fs.ReadByte());
  3934. // Ensure we've reached end of the stream
  3935. Assert.AreEqual(-1, fs.ReadByte());
  3936. }
  3937. client.DeleteFile(remoteFile);
  3938. // create single-byte file
  3939. using (var fs = client.OpenWrite(remoteFile))
  3940. {
  3941. fs.WriteByte(0x04);
  3942. }
  3943. // seek beyond EOF but not beyond buffer size
  3944. // write less bytes than buffer size
  3945. var seekOffset = 3L;
  3946. // buffer holding the data that we'll write to the file
  3947. var writeBuffer = GenerateRandom(size: 7);
  3948. using (var fs = client.OpenWrite(remoteFile))
  3949. {
  3950. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3951. Assert.AreEqual(4, newPosition);
  3952. Assert.AreEqual(4, fs.Position);
  3953. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3954. }
  3955. using (var fs = client.OpenRead(remoteFile))
  3956. {
  3957. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3958. Assert.AreEqual(0x04, fs.ReadByte());
  3959. var soughtOverReadBuffer = new byte[seekOffset];
  3960. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3961. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3962. var readBuffer = new byte[writeBuffer.Length];
  3963. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3964. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3965. // Ensure we've reached end of the stream
  3966. Assert.AreEqual(-1, fs.ReadByte());
  3967. }
  3968. client.DeleteFile(remoteFile);
  3969. // create single-byte file
  3970. using (var fs = client.OpenWrite(remoteFile))
  3971. {
  3972. fs.WriteByte(0x04);
  3973. }
  3974. // seek beyond EOF and beyond buffer size
  3975. // write less bytes than buffer size
  3976. seekOffset = 700L;
  3977. // buffer holding the data that we'll write to the file
  3978. writeBuffer = GenerateRandom(size: 4);
  3979. using (var fs = client.OpenWrite(remoteFile))
  3980. {
  3981. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3982. Assert.AreEqual(1 + seekOffset, newPosition);
  3983. Assert.AreEqual(1 + seekOffset, fs.Position);
  3984. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3985. }
  3986. using (var fs = client.OpenRead(remoteFile))
  3987. {
  3988. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3989. Assert.AreEqual(0x04, fs.ReadByte());
  3990. var soughtOverReadBuffer = new byte[seekOffset];
  3991. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  3992. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  3993. var readBuffer = new byte[writeBuffer.Length];
  3994. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  3995. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  3996. // Ensure we've reached end of the stream
  3997. Assert.AreEqual(-1, fs.ReadByte());
  3998. }
  3999. client.DeleteFile(remoteFile);
  4000. // create single-byte file
  4001. using (var fs = client.OpenWrite(remoteFile))
  4002. {
  4003. fs.WriteByte(0x04);
  4004. }
  4005. // seek beyond EOF but not beyond buffer size
  4006. // write more bytes than buffer size
  4007. seekOffset = 3L;
  4008. writeBuffer = GenerateRandom(size: 600);
  4009. using (var fs = client.OpenWrite(remoteFile))
  4010. {
  4011. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  4012. Assert.AreEqual(1 + seekOffset, newPosition);
  4013. Assert.AreEqual(1 + seekOffset, fs.Position);
  4014. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4015. }
  4016. using (var fs = client.OpenRead(remoteFile))
  4017. {
  4018. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  4019. Assert.AreEqual(0x04, fs.ReadByte());
  4020. var soughtOverReadBuffer = new byte[seekOffset];
  4021. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4022. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4023. var readBuffer = new byte[writeBuffer.Length];
  4024. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4025. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4026. // Ensure we've reached end of the stream
  4027. Assert.AreEqual(-1, fs.ReadByte());
  4028. }
  4029. client.DeleteFile(remoteFile);
  4030. // create single-byte file
  4031. using (var fs = client.OpenWrite(remoteFile))
  4032. {
  4033. fs.WriteByte(0x04);
  4034. }
  4035. // seek beyond EOF and beyond buffer size
  4036. // write more bytes than buffer size
  4037. seekOffset = 550L;
  4038. writeBuffer = GenerateRandom(size: 600);
  4039. using (var fs = client.OpenWrite(remoteFile))
  4040. {
  4041. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  4042. Assert.AreEqual(1 + seekOffset, newPosition);
  4043. Assert.AreEqual(1 + seekOffset, fs.Position);
  4044. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4045. }
  4046. using (var fs = client.OpenRead(remoteFile))
  4047. {
  4048. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  4049. Assert.AreEqual(0x04, fs.ReadByte());
  4050. var soughtOverReadBuffer = new byte[seekOffset];
  4051. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4052. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4053. var readBuffer = new byte[writeBuffer.Length];
  4054. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4055. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4056. // Ensure we've reached end of the stream
  4057. Assert.AreEqual(-1, fs.ReadByte());
  4058. }
  4059. }
  4060. finally
  4061. {
  4062. if (client.Exists(remoteFile))
  4063. {
  4064. client.DeleteFile(remoteFile);
  4065. }
  4066. }
  4067. }
  4068. }
  4069. [TestMethod]
  4070. public void Sftp_SftpFileStream_Seek_NegativeOffSet_SeekOriginEnd()
  4071. {
  4072. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4073. {
  4074. client.BufferSize = 500;
  4075. client.Connect();
  4076. var remoteFile = GenerateUniqueRemoteFileName();
  4077. if (client.Exists(remoteFile))
  4078. {
  4079. client.DeleteFile(remoteFile);
  4080. }
  4081. try
  4082. {
  4083. using (var fs = client.OpenWrite(remoteFile))
  4084. {
  4085. fs.WriteByte(0x04);
  4086. fs.WriteByte(0x07);
  4087. fs.WriteByte(0x05);
  4088. }
  4089. // seek within file and not beyond buffer size
  4090. // do not write anything
  4091. using (var fs = client.OpenWrite(remoteFile))
  4092. {
  4093. var newPosition = fs.Seek(offset: -2L, SeekOrigin.End);
  4094. Assert.AreEqual(1, newPosition);
  4095. Assert.AreEqual(1, fs.Position);
  4096. }
  4097. using (var fs = client.OpenRead(remoteFile))
  4098. {
  4099. Assert.AreEqual(3, fs.Length);
  4100. Assert.AreEqual(0x04, fs.ReadByte());
  4101. Assert.AreEqual(0x07, fs.ReadByte());
  4102. Assert.AreEqual(0x05, fs.ReadByte());
  4103. // Ensure we've reached end of the stream
  4104. Assert.AreEqual(-1, fs.ReadByte());
  4105. }
  4106. client.DeleteFile(remoteFile);
  4107. // buffer holding the data that we'll write to the file
  4108. var writeBuffer = GenerateRandom(size: (int)client.BufferSize + 200);
  4109. using (var fs = client.OpenWrite(remoteFile))
  4110. {
  4111. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4112. }
  4113. // seek within EOF and beyond buffer size
  4114. // do not write anything
  4115. using (var fs = client.OpenWrite(remoteFile))
  4116. {
  4117. var newPosition = fs.Seek(offset: -100L, SeekOrigin.End);
  4118. Assert.AreEqual(600, newPosition);
  4119. Assert.AreEqual(600, fs.Position);
  4120. }
  4121. using (var fs = client.OpenRead(remoteFile))
  4122. {
  4123. Assert.AreEqual(writeBuffer.Length, fs.Length);
  4124. var readBuffer = new byte[writeBuffer.Length];
  4125. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4126. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4127. // Ensure we've reached end of the stream
  4128. Assert.AreEqual(-1, fs.ReadByte());
  4129. }
  4130. client.DeleteFile(remoteFile);
  4131. // seek within EOF and within buffer size
  4132. // write less bytes than buffer size
  4133. using (var fs = client.OpenWrite(remoteFile))
  4134. {
  4135. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4136. var newPosition = fs.Seek(offset: -3, SeekOrigin.End);
  4137. Assert.AreEqual(697, newPosition);
  4138. Assert.AreEqual(697, fs.Position);
  4139. fs.WriteByte(0x01);
  4140. fs.WriteByte(0x05);
  4141. fs.WriteByte(0x04);
  4142. fs.WriteByte(0x07);
  4143. }
  4144. using (var fs = client.OpenRead(remoteFile))
  4145. {
  4146. Assert.AreEqual(writeBuffer.Length + 1, fs.Length);
  4147. var readBuffer = new byte[writeBuffer.Length - 3];
  4148. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4149. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Take(readBuffer.Length)));
  4150. Assert.AreEqual(0x01, fs.ReadByte());
  4151. Assert.AreEqual(0x05, fs.ReadByte());
  4152. Assert.AreEqual(0x04, fs.ReadByte());
  4153. Assert.AreEqual(0x07, fs.ReadByte());
  4154. // Ensure we've reached end of the stream
  4155. Assert.AreEqual(-1, fs.ReadByte());
  4156. }
  4157. client.DeleteFile(remoteFile);
  4158. // buffer holding the data that we'll write to the file
  4159. writeBuffer = GenerateRandom(size: (int)client.BufferSize * 4);
  4160. // seek within EOF and beyond buffer size
  4161. // write less bytes than buffer size
  4162. using (var fs = client.OpenWrite(remoteFile))
  4163. {
  4164. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4165. var newPosition = fs.Seek(offset: -(client.BufferSize * 2), SeekOrigin.End);
  4166. Assert.AreEqual(1000, newPosition);
  4167. Assert.AreEqual(1000, fs.Position);
  4168. fs.WriteByte(0x01);
  4169. fs.WriteByte(0x05);
  4170. fs.WriteByte(0x04);
  4171. fs.WriteByte(0x07);
  4172. }
  4173. using (var fs = client.OpenRead(remoteFile))
  4174. {
  4175. Assert.AreEqual(writeBuffer.Length, fs.Length);
  4176. // First part of file should not have been touched
  4177. var readBuffer = new byte[(int)client.BufferSize * 2];
  4178. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4179. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Take(readBuffer.Length)));
  4180. // Check part that should have been updated
  4181. Assert.AreEqual(0x01, fs.ReadByte());
  4182. Assert.AreEqual(0x05, fs.ReadByte());
  4183. Assert.AreEqual(0x04, fs.ReadByte());
  4184. Assert.AreEqual(0x07, fs.ReadByte());
  4185. // Remaining bytes should not have been touched
  4186. readBuffer = new byte[((int)client.BufferSize * 2) - 4];
  4187. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4188. Assert.IsTrue(readBuffer.SequenceEqual(writeBuffer.Skip(((int)client.BufferSize * 2) + 4).Take(readBuffer.Length)));
  4189. // Ensure we've reached end of the stream
  4190. Assert.AreEqual(-1, fs.ReadByte());
  4191. }
  4192. }
  4193. finally
  4194. {
  4195. if (client.Exists(remoteFile))
  4196. {
  4197. client.DeleteFile(remoteFile);
  4198. }
  4199. }
  4200. }
  4201. }
  4202. /// https://github.com/sshnet/SSH.NET/issues/253
  4203. [TestMethod]
  4204. public void Sftp_SftpFileStream_Seek_Issue253()
  4205. {
  4206. var buf = Encoding.UTF8.GetBytes("123456");
  4207. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4208. {
  4209. client.Connect();
  4210. var remoteFile = GenerateUniqueRemoteFileName();
  4211. if (client.Exists(remoteFile))
  4212. {
  4213. client.DeleteFile(remoteFile);
  4214. }
  4215. try
  4216. {
  4217. using (var ws = client.OpenWrite(remoteFile))
  4218. {
  4219. ws.Write(buf, offset: 0, count: 3);
  4220. }
  4221. using (var ws = client.OpenWrite(remoteFile))
  4222. {
  4223. var newPosition = ws.Seek(offset: 3, SeekOrigin.Begin);
  4224. Assert.AreEqual(3, newPosition);
  4225. Assert.AreEqual(3, ws.Position);
  4226. ws.Write(buf, 3, 3);
  4227. }
  4228. var actual = client.ReadAllText(remoteFile, Encoding.UTF8);
  4229. Assert.AreEqual("123456", actual);
  4230. }
  4231. finally
  4232. {
  4233. if (client.Exists(remoteFile))
  4234. {
  4235. client.DeleteFile(remoteFile);
  4236. }
  4237. }
  4238. }
  4239. }
  4240. [TestMethod]
  4241. public void Sftp_SftpFileStream_Seek_WithinReadBuffer()
  4242. {
  4243. var originalContent = GenerateRandom(size: 800);
  4244. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4245. {
  4246. client.BufferSize = 500;
  4247. client.Connect();
  4248. var remoteFile = GenerateUniqueRemoteFileName();
  4249. if (client.Exists(remoteFile))
  4250. {
  4251. client.DeleteFile(remoteFile);
  4252. }
  4253. try
  4254. {
  4255. using (var fs = client.OpenWrite(remoteFile))
  4256. {
  4257. fs.Write(originalContent, offset: 0, originalContent.Length);
  4258. }
  4259. using (var fs = client.OpenRead(remoteFile))
  4260. {
  4261. var readBuffer = new byte[200];
  4262. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4263. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  4264. Assert.AreEqual(3L, newPosition);
  4265. Assert.AreEqual(3L, fs.Position);
  4266. }
  4267. client.DeleteFile(remoteFile);
  4268. #region Seek beyond EOF and beyond buffer size do not write anything
  4269. // create single-byte file
  4270. using (var fs = client.OpenWrite(remoteFile))
  4271. {
  4272. fs.WriteByte(0x04);
  4273. }
  4274. using (var fs = client.OpenRead(remoteFile))
  4275. {
  4276. Assert.AreEqual(1, fs.Length);
  4277. Assert.AreEqual(0x04, fs.ReadByte());
  4278. // Ensure we've reached end of the stream
  4279. Assert.AreEqual(-1, fs.ReadByte());
  4280. }
  4281. using (var fs = client.OpenWrite(remoteFile))
  4282. {
  4283. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  4284. Assert.AreEqual(700L, newPosition);
  4285. Assert.AreEqual(700L, fs.Position);
  4286. }
  4287. using (var fs = client.OpenRead(remoteFile))
  4288. {
  4289. Assert.AreEqual(1, fs.Length);
  4290. Assert.AreEqual(0x04, fs.ReadByte());
  4291. // Ensure we've reached end of the stream
  4292. Assert.AreEqual(-1, fs.ReadByte());
  4293. }
  4294. client.DeleteFile(remoteFile);
  4295. #endregion Seek beyond EOF and beyond buffer size do not write anything
  4296. #region Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4297. // create single-byte file
  4298. using (var fs = client.OpenWrite(remoteFile))
  4299. {
  4300. fs.WriteByte(0x04);
  4301. }
  4302. var seekOffset = 3L;
  4303. var writeBuffer = GenerateRandom(size: 7);
  4304. using (var fs = client.OpenWrite(remoteFile))
  4305. {
  4306. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4307. Assert.AreEqual(seekOffset, newPosition);
  4308. Assert.AreEqual(seekOffset, fs.Position);
  4309. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4310. }
  4311. using (var fs = client.OpenRead(remoteFile))
  4312. {
  4313. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4314. Assert.AreEqual(0x04, fs.ReadByte());
  4315. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4316. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4317. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4318. var readBuffer = new byte[writeBuffer.Length];
  4319. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4320. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4321. // Ensure we've reached end of the stream
  4322. Assert.AreEqual(-1, fs.ReadByte());
  4323. }
  4324. client.DeleteFile(remoteFile);
  4325. #endregion Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4326. #region Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4327. // create single-byte file
  4328. using (var fs = client.OpenWrite(remoteFile))
  4329. {
  4330. fs.WriteByte(0x04);
  4331. }
  4332. seekOffset = 700L;
  4333. writeBuffer = GenerateRandom(size: 4);
  4334. using (var fs = client.OpenWrite(remoteFile))
  4335. {
  4336. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4337. Assert.AreEqual(seekOffset, newPosition);
  4338. Assert.AreEqual(seekOffset, fs.Position);
  4339. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4340. }
  4341. using (var fs = client.OpenRead(remoteFile))
  4342. {
  4343. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4344. Assert.AreEqual(0x04, fs.ReadByte());
  4345. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4346. Assert.AreEqual(soughtOverReadBuffer.Length, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4347. Assert.IsTrue(new byte[soughtOverReadBuffer.Length].IsEqualTo(soughtOverReadBuffer));
  4348. var readBuffer = new byte[writeBuffer.Length];
  4349. Assert.AreEqual(readBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4350. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4351. // Ensure we've reached end of the stream
  4352. Assert.AreEqual(-1, fs.ReadByte());
  4353. }
  4354. client.DeleteFile(remoteFile);
  4355. #endregion Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4356. #region Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4357. // create single-byte file
  4358. using (var fs = client.OpenWrite(remoteFile))
  4359. {
  4360. fs.WriteByte(0x04);
  4361. }
  4362. seekOffset = 3L;
  4363. writeBuffer = GenerateRandom(size: 600);
  4364. using (var fs = client.OpenWrite(remoteFile))
  4365. {
  4366. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4367. Assert.AreEqual(seekOffset, newPosition);
  4368. Assert.AreEqual(seekOffset, fs.Position);
  4369. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4370. }
  4371. using (var fs = client.OpenRead(remoteFile))
  4372. {
  4373. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4374. Assert.AreEqual(0x04, fs.ReadByte());
  4375. Assert.AreEqual(0x00, fs.ReadByte());
  4376. Assert.AreEqual(0x00, fs.ReadByte());
  4377. var readBuffer = new byte[writeBuffer.Length];
  4378. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4379. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4380. // Ensure we've reached end of the stream
  4381. Assert.AreEqual(-1, fs.ReadByte());
  4382. }
  4383. client.DeleteFile(remoteFile);
  4384. #endregion Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4385. #region Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4386. // create single-byte file
  4387. using (var fs = client.OpenWrite(remoteFile))
  4388. {
  4389. fs.WriteByte(0x04);
  4390. }
  4391. seekOffset = 550L;
  4392. writeBuffer = GenerateRandom(size: 600);
  4393. using (var fs = client.OpenWrite(remoteFile))
  4394. {
  4395. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4396. Assert.AreEqual(seekOffset, newPosition);
  4397. Assert.AreEqual(seekOffset, fs.Position);
  4398. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4399. }
  4400. using (var fs = client.OpenRead(remoteFile))
  4401. {
  4402. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4403. Assert.AreEqual(0x04, fs.ReadByte());
  4404. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4405. Assert.AreEqual(seekOffset - 1, fs.Read(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length));
  4406. Assert.IsTrue(new byte[seekOffset - 1].IsEqualTo(soughtOverReadBuffer));
  4407. var readBuffer = new byte[writeBuffer.Length];
  4408. Assert.AreEqual(writeBuffer.Length, fs.Read(readBuffer, offset: 0, readBuffer.Length));
  4409. Assert.IsTrue(writeBuffer.IsEqualTo(readBuffer));
  4410. // Ensure we've reached end of the stream
  4411. Assert.AreEqual(-1, fs.ReadByte());
  4412. }
  4413. client.DeleteFile(remoteFile);
  4414. #endregion Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4415. }
  4416. finally
  4417. {
  4418. if (client.Exists(remoteFile))
  4419. {
  4420. client.DeleteFile(remoteFile);
  4421. }
  4422. }
  4423. }
  4424. }
  4425. [TestMethod]
  4426. public void Sftp_SftpFileStream_SetLength_FileDoesNotExist()
  4427. {
  4428. var size = new Random().Next(500, 5000);
  4429. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4430. {
  4431. client.Connect();
  4432. var remoteFile = GenerateUniqueRemoteFileName();
  4433. if (client.Exists(remoteFile))
  4434. {
  4435. client.DeleteFile(remoteFile);
  4436. }
  4437. try
  4438. {
  4439. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4440. {
  4441. s.SetLength(size);
  4442. }
  4443. Assert.IsTrue(client.Exists(remoteFile));
  4444. var attributes = client.GetAttributes(remoteFile);
  4445. Assert.IsTrue(attributes.IsRegularFile);
  4446. Assert.AreEqual(size, attributes.Size);
  4447. using (var downloaded = new MemoryStream())
  4448. {
  4449. client.DownloadFile(remoteFile, downloaded);
  4450. downloaded.Position = 0;
  4451. Assert.AreEqual(CreateHash(new byte[size]), CreateHash(downloaded));
  4452. }
  4453. }
  4454. finally
  4455. {
  4456. if (client.Exists(remoteFile))
  4457. {
  4458. client.DeleteFile(remoteFile);
  4459. }
  4460. }
  4461. }
  4462. }
  4463. [TestMethod]
  4464. public void Sftp_Open_Append_Write_ExistingFile()
  4465. {
  4466. const int fileSize = 5 * 1024;
  4467. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4468. using (var input = CreateMemoryStream(fileSize))
  4469. {
  4470. input.Position = 0;
  4471. client.Connect();
  4472. var remoteFile = GenerateUniqueRemoteFileName();
  4473. if (client.Exists(remoteFile))
  4474. {
  4475. client.DeleteFile(remoteFile);
  4476. }
  4477. try
  4478. {
  4479. client.UploadFile(input, remoteFile);
  4480. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4481. {
  4482. var buffer = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4483. s.Write(buffer, offset: 0, buffer.Length);
  4484. input.Write(buffer, offset: 0, buffer.Length);
  4485. }
  4486. using (var downloaded = new MemoryStream())
  4487. {
  4488. client.DownloadFile(remoteFile, downloaded);
  4489. input.Position = 0;
  4490. downloaded.Position = 0;
  4491. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4492. }
  4493. }
  4494. finally
  4495. {
  4496. if (client.Exists(remoteFile))
  4497. {
  4498. client.DeleteFile(remoteFile);
  4499. }
  4500. }
  4501. }
  4502. }
  4503. [TestMethod]
  4504. public void Sftp_Open_Append_Write_FileDoesNotExist()
  4505. {
  4506. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4507. {
  4508. client.Connect();
  4509. var remoteFile = GenerateUniqueRemoteFileName();
  4510. if (client.Exists(remoteFile))
  4511. {
  4512. client.DeleteFile(remoteFile);
  4513. }
  4514. try
  4515. {
  4516. #region Verify if merely opening the file for append creates a zero-byte file
  4517. using (client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4518. {
  4519. }
  4520. Assert.IsTrue(client.Exists(remoteFile));
  4521. var attributes = client.GetAttributes(remoteFile);
  4522. Assert.IsTrue(attributes.IsRegularFile);
  4523. Assert.AreEqual(0L, attributes.Size);
  4524. #endregion Verify if merely opening the file for append creates it
  4525. client.DeleteFile(remoteFile);
  4526. #region Verify if content is actually written to the file
  4527. var content = GenerateRandom(size: 100);
  4528. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4529. {
  4530. s.Write(content, offset: 0, content.Length);
  4531. }
  4532. using (var downloaded = new MemoryStream())
  4533. {
  4534. client.DownloadFile(remoteFile, downloaded);
  4535. downloaded.Position = 0;
  4536. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4537. }
  4538. #endregion Verify if content is actually written to the file
  4539. }
  4540. finally
  4541. {
  4542. if (client.Exists(remoteFile))
  4543. {
  4544. client.DeleteFile(remoteFile);
  4545. }
  4546. }
  4547. }
  4548. }
  4549. [TestMethod]
  4550. public void Sftp_Open_PathAndMode_ModeIsCreate_FileDoesNotExist()
  4551. {
  4552. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4553. {
  4554. client.Connect();
  4555. var remoteFile = GenerateUniqueRemoteFileName();
  4556. if (client.Exists(remoteFile))
  4557. {
  4558. client.DeleteFile(remoteFile);
  4559. }
  4560. try
  4561. {
  4562. #region Verify if merely opening the file for create creates a zero-byte file
  4563. using (client.Open(remoteFile, FileMode.Create))
  4564. {
  4565. }
  4566. Assert.IsTrue(client.Exists(remoteFile));
  4567. var attributes = client.GetAttributes(remoteFile);
  4568. Assert.IsTrue(attributes.IsRegularFile);
  4569. Assert.AreEqual(0L, attributes.Size);
  4570. #endregion Verify if merely opening the file for create creates a zero-byte file
  4571. client.DeleteFile(remoteFile);
  4572. #region Verify if content is actually written to the file
  4573. var content = GenerateRandom(size: 100);
  4574. using (var s = client.Open(remoteFile, FileMode.Create))
  4575. {
  4576. s.Write(content, offset: 0, content.Length);
  4577. }
  4578. using (var downloaded = new MemoryStream())
  4579. {
  4580. client.DownloadFile(remoteFile, downloaded);
  4581. downloaded.Position = 0;
  4582. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4583. }
  4584. #endregion Verify if content is actually written to the file
  4585. }
  4586. finally
  4587. {
  4588. if (client.Exists(remoteFile))
  4589. {
  4590. client.DeleteFile(remoteFile);
  4591. }
  4592. }
  4593. }
  4594. }
  4595. [TestMethod]
  4596. public void Sftp_Open_PathAndMode_ModeIsCreate_ExistingFile()
  4597. {
  4598. const int fileSize = 5 * 1024;
  4599. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4600. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4601. using (var input = CreateMemoryStream(fileSize))
  4602. {
  4603. client.Connect();
  4604. var remoteFile = GenerateUniqueRemoteFileName();
  4605. if (client.Exists(remoteFile))
  4606. {
  4607. client.DeleteFile(remoteFile);
  4608. }
  4609. try
  4610. {
  4611. input.Position = 0;
  4612. client.UploadFile(input, remoteFile);
  4613. using (var stream = client.Open(remoteFile, FileMode.Create))
  4614. {
  4615. // Verify if merely opening the file for create overwrites the file
  4616. var attributes = client.GetAttributes(remoteFile);
  4617. Assert.IsTrue(attributes.IsRegularFile);
  4618. Assert.AreEqual(0L, attributes.Size);
  4619. stream.Write(newContent, offset: 0, newContent.Length);
  4620. stream.Position = 0;
  4621. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4622. }
  4623. }
  4624. finally
  4625. {
  4626. if (client.Exists(remoteFile))
  4627. {
  4628. client.DeleteFile(remoteFile);
  4629. }
  4630. }
  4631. }
  4632. }
  4633. [TestMethod]
  4634. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_FileDoesNotExist()
  4635. {
  4636. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4637. {
  4638. client.Connect();
  4639. var remoteFile = GenerateUniqueRemoteFileName();
  4640. if (client.Exists(remoteFile))
  4641. {
  4642. client.DeleteFile(remoteFile);
  4643. }
  4644. try
  4645. {
  4646. #region Verify if merely opening the file for create creates a zero-byte file
  4647. using (client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4648. {
  4649. }
  4650. Assert.IsTrue(client.Exists(remoteFile));
  4651. var attributes = client.GetAttributes(remoteFile);
  4652. Assert.IsTrue(attributes.IsRegularFile);
  4653. Assert.AreEqual(0L, attributes.Size);
  4654. #endregion Verify if merely opening the file for create creates a zero-byte file
  4655. client.DeleteFile(remoteFile);
  4656. #region Verify if content is actually written to the file
  4657. var content = GenerateRandom(size: 100);
  4658. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4659. {
  4660. s.Write(content, offset: 0, content.Length);
  4661. }
  4662. using (var downloaded = new MemoryStream())
  4663. {
  4664. client.DownloadFile(remoteFile, downloaded);
  4665. downloaded.Position = 0;
  4666. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4667. }
  4668. #endregion Verify if content is actually written to the file
  4669. }
  4670. finally
  4671. {
  4672. if (client.Exists(remoteFile))
  4673. {
  4674. client.DeleteFile(remoteFile);
  4675. }
  4676. }
  4677. }
  4678. }
  4679. [TestMethod]
  4680. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_ExistingFile()
  4681. {
  4682. const int fileSize = 5 * 1024;
  4683. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4684. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4685. using (var input = CreateMemoryStream(fileSize))
  4686. {
  4687. client.Connect();
  4688. var remoteFile = GenerateUniqueRemoteFileName();
  4689. if (client.Exists(remoteFile))
  4690. {
  4691. client.DeleteFile(remoteFile);
  4692. }
  4693. try
  4694. {
  4695. input.Position = 0;
  4696. client.UploadFile(input, remoteFile);
  4697. using (var stream = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4698. {
  4699. // Verify if merely opening the file for create overwrites the file
  4700. var attributes = client.GetAttributes(remoteFile);
  4701. Assert.IsTrue(attributes.IsRegularFile);
  4702. Assert.AreEqual(0L, attributes.Size);
  4703. stream.Write(newContent, offset: 0, newContent.Length);
  4704. stream.Position = 0;
  4705. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4706. }
  4707. }
  4708. finally
  4709. {
  4710. if (client.Exists(remoteFile))
  4711. {
  4712. client.DeleteFile(remoteFile);
  4713. }
  4714. }
  4715. }
  4716. }
  4717. [TestMethod]
  4718. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_ExistingFile()
  4719. {
  4720. // use new content that contains less bytes than original content to
  4721. // verify whether file is first truncated
  4722. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4723. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4724. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4725. {
  4726. client.Connect();
  4727. var remoteFile = GenerateUniqueRemoteFileName();
  4728. if (client.Exists(remoteFile))
  4729. {
  4730. client.DeleteFile(remoteFile);
  4731. }
  4732. try
  4733. {
  4734. client.WriteAllBytes(remoteFile, originalContent);
  4735. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4736. {
  4737. s.Write(newContent, offset: 0, newContent.Length);
  4738. }
  4739. using (var downloaded = new MemoryStream())
  4740. {
  4741. client.DownloadFile(remoteFile, downloaded);
  4742. downloaded.Position = 0;
  4743. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4744. }
  4745. }
  4746. finally
  4747. {
  4748. if (client.Exists(remoteFile))
  4749. {
  4750. client.DeleteFile(remoteFile);
  4751. }
  4752. }
  4753. }
  4754. }
  4755. [TestMethod]
  4756. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_FileDoesNotExist()
  4757. {
  4758. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4759. {
  4760. client.Connect();
  4761. var remoteFile = GenerateUniqueRemoteFileName();
  4762. if (client.Exists(remoteFile))
  4763. {
  4764. client.DeleteFile(remoteFile);
  4765. }
  4766. try
  4767. {
  4768. #region Verify if merely opening the file for create creates a zero-byte file
  4769. using (client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4770. {
  4771. }
  4772. Assert.IsTrue(client.Exists(remoteFile));
  4773. var attributes = client.GetAttributes(remoteFile);
  4774. Assert.IsTrue(attributes.IsRegularFile);
  4775. Assert.AreEqual(0L, attributes.Size);
  4776. #endregion Verify if merely opening the file for create creates a zero-byte file
  4777. client.DeleteFile(remoteFile);
  4778. #region Verify if content is actually written to the file
  4779. var content = GenerateRandom(size: 100);
  4780. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4781. {
  4782. s.Write(content, offset: 0, content.Length);
  4783. }
  4784. using (var downloaded = new MemoryStream())
  4785. {
  4786. client.DownloadFile(remoteFile, downloaded);
  4787. downloaded.Position = 0;
  4788. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4789. }
  4790. #endregion Verify if content is actually written to the file
  4791. }
  4792. finally
  4793. {
  4794. if (client.Exists(remoteFile))
  4795. {
  4796. client.DeleteFile(remoteFile);
  4797. }
  4798. }
  4799. }
  4800. }
  4801. [TestMethod]
  4802. public void Sftp_Open_CreateNew_Write_ExistingFile()
  4803. {
  4804. const int fileSize = 5 * 1024;
  4805. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4806. using (var input = CreateMemoryStream(fileSize))
  4807. {
  4808. client.Connect();
  4809. var remoteFile = GenerateUniqueRemoteFileName();
  4810. if (client.Exists(remoteFile))
  4811. {
  4812. client.DeleteFile(remoteFile);
  4813. }
  4814. input.Position = 0;
  4815. try
  4816. {
  4817. client.UploadFile(input, remoteFile);
  4818. Stream stream = null;
  4819. try
  4820. {
  4821. stream = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write);
  4822. Assert.Fail();
  4823. }
  4824. catch (SshException)
  4825. {
  4826. }
  4827. finally
  4828. {
  4829. stream?.Dispose();
  4830. }
  4831. // Verify that the file was not modified
  4832. using (var downloaded = new MemoryStream())
  4833. {
  4834. client.DownloadFile(remoteFile, downloaded);
  4835. input.Position = 0;
  4836. downloaded.Position = 0;
  4837. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4838. }
  4839. }
  4840. finally
  4841. {
  4842. if (client.Exists(remoteFile))
  4843. {
  4844. client.DeleteFile(remoteFile);
  4845. }
  4846. }
  4847. }
  4848. }
  4849. [TestMethod]
  4850. public void Sftp_Open_CreateNew_Write_FileDoesNotExist()
  4851. {
  4852. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4853. {
  4854. client.Connect();
  4855. var remoteFile = GenerateUniqueRemoteFileName();
  4856. if (client.Exists(remoteFile))
  4857. {
  4858. client.DeleteFile(remoteFile);
  4859. }
  4860. try
  4861. {
  4862. #region Verify if merely opening the file creates a zero-byte file
  4863. using (client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4864. {
  4865. }
  4866. Assert.IsTrue(client.Exists(remoteFile));
  4867. var attributes = client.GetAttributes(remoteFile);
  4868. Assert.IsTrue(attributes.IsRegularFile);
  4869. Assert.AreEqual(0L, attributes.Size);
  4870. #endregion Verify if merely opening the file creates it
  4871. client.DeleteFile(remoteFile);
  4872. #region Verify if content is actually written to the file
  4873. var content = GenerateRandom(size: 100);
  4874. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4875. {
  4876. s.Write(content, offset: 0, content.Length);
  4877. }
  4878. using (var downloaded = new MemoryStream())
  4879. {
  4880. client.DownloadFile(remoteFile, downloaded);
  4881. downloaded.Position = 0;
  4882. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4883. }
  4884. #endregion Verify if content is actually written to the file
  4885. }
  4886. finally
  4887. {
  4888. if (client.Exists(remoteFile))
  4889. {
  4890. client.DeleteFile(remoteFile);
  4891. }
  4892. }
  4893. }
  4894. }
  4895. [TestMethod]
  4896. public void Sftp_Open_Open_Write_ExistingFile()
  4897. {
  4898. // use new content that contains less bytes than original content to
  4899. // verify whether file is first truncated
  4900. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4901. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4902. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4903. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4904. {
  4905. client.Connect();
  4906. var remoteFile = GenerateUniqueRemoteFileName();
  4907. if (client.Exists(remoteFile))
  4908. {
  4909. client.DeleteFile(remoteFile);
  4910. }
  4911. try
  4912. {
  4913. client.WriteAllBytes(remoteFile, originalContent);
  4914. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  4915. {
  4916. s.Write(newContent, offset: 0, newContent.Length);
  4917. }
  4918. using (var downloaded = new MemoryStream())
  4919. {
  4920. client.DownloadFile(remoteFile, downloaded);
  4921. downloaded.Position = 0;
  4922. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4923. }
  4924. }
  4925. finally
  4926. {
  4927. if (client.Exists(remoteFile))
  4928. {
  4929. client.DeleteFile(remoteFile);
  4930. }
  4931. }
  4932. }
  4933. }
  4934. [TestMethod]
  4935. public void Sftp_Open_Open_Write_FileDoesNotExist()
  4936. {
  4937. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4938. {
  4939. client.Connect();
  4940. var remoteFile = GenerateUniqueRemoteFileName();
  4941. if (client.Exists(remoteFile))
  4942. {
  4943. client.DeleteFile(remoteFile);
  4944. }
  4945. try
  4946. {
  4947. Stream stream = null;
  4948. try
  4949. {
  4950. stream = client.Open(remoteFile, FileMode.Open, FileAccess.Write);
  4951. Assert.Fail();
  4952. }
  4953. catch (SshException)
  4954. {
  4955. }
  4956. finally
  4957. {
  4958. stream?.Dispose();
  4959. }
  4960. Assert.IsFalse(client.Exists(remoteFile));
  4961. }
  4962. finally
  4963. {
  4964. if (client.Exists(remoteFile))
  4965. {
  4966. client.DeleteFile(remoteFile);
  4967. }
  4968. }
  4969. }
  4970. }
  4971. [TestMethod]
  4972. public void Sftp_Open_OpenOrCreate_Write_ExistingFile()
  4973. {
  4974. // use new content that contains less bytes than original content to
  4975. // verify whether file is first truncated
  4976. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4977. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4978. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4979. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4980. {
  4981. client.Connect();
  4982. var remoteFile = GenerateUniqueRemoteFileName();
  4983. if (client.Exists(remoteFile))
  4984. {
  4985. client.DeleteFile(remoteFile);
  4986. }
  4987. try
  4988. {
  4989. client.WriteAllBytes(remoteFile, originalContent);
  4990. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4991. {
  4992. s.Write(newContent, offset: 0, newContent.Length);
  4993. }
  4994. using (var downloaded = new MemoryStream())
  4995. {
  4996. client.DownloadFile(remoteFile, downloaded);
  4997. downloaded.Position = 0;
  4998. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4999. }
  5000. }
  5001. finally
  5002. {
  5003. if (client.Exists(remoteFile))
  5004. {
  5005. client.DeleteFile(remoteFile);
  5006. }
  5007. }
  5008. }
  5009. }
  5010. [TestMethod]
  5011. public void Sftp_Open_OpenOrCreate_Write_FileDoesNotExist()
  5012. {
  5013. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  5014. {
  5015. client.Connect();
  5016. var remoteFile = GenerateUniqueRemoteFileName();
  5017. if (client.Exists(remoteFile))
  5018. {
  5019. client.DeleteFile(remoteFile);
  5020. }
  5021. try
  5022. {
  5023. #region Verify if merely opening the file creates a zero-byte file
  5024. using (client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  5025. {
  5026. }
  5027. Assert.IsTrue(client.Exists(remoteFile));
  5028. var attributes = client.GetAttributes(remoteFile);
  5029. Assert.IsTrue(attributes.IsRegularFile);
  5030. Assert.AreEqual(0L, attributes.Size);
  5031. #endregion Verify if merely opening the file creates it
  5032. client.DeleteFile(remoteFile);
  5033. #region Verify if content is actually written to the file
  5034. var content = GenerateRandom(size: 100);
  5035. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  5036. {
  5037. s.Write(content, offset: 0, content.Length);
  5038. }
  5039. using (var downloaded = new MemoryStream())
  5040. {
  5041. client.DownloadFile(remoteFile, downloaded);
  5042. downloaded.Position = 0;
  5043. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  5044. }
  5045. #endregion Verify if content is actually written to the file
  5046. }
  5047. finally
  5048. {
  5049. if (client.Exists(remoteFile))
  5050. {
  5051. client.DeleteFile(remoteFile);
  5052. }
  5053. }
  5054. }
  5055. }
  5056. [TestMethod]
  5057. public void Sftp_Open_Truncate_Write_ExistingFile()
  5058. {
  5059. const int fileSize = 5 * 1024;
  5060. // use new content that contains less bytes than original content to
  5061. // verify whether file is first truncated
  5062. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  5063. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  5064. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  5065. using (var input = CreateMemoryStream(fileSize))
  5066. {
  5067. client.Connect();
  5068. var remoteFile = GenerateUniqueRemoteFileName();
  5069. if (client.Exists(remoteFile))
  5070. {
  5071. client.DeleteFile(remoteFile);
  5072. }
  5073. input.Position = 0;
  5074. try
  5075. {
  5076. client.WriteAllBytes(remoteFile, originalContent);
  5077. using (var s = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write))
  5078. {
  5079. s.Write(newContent, offset: 0, newContent.Length);
  5080. }
  5081. using (var downloaded = new MemoryStream())
  5082. {
  5083. client.DownloadFile(remoteFile, downloaded);
  5084. input.Position = 0;
  5085. downloaded.Position = 0;
  5086. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  5087. }
  5088. }
  5089. finally
  5090. {
  5091. if (client.Exists(remoteFile))
  5092. {
  5093. client.DeleteFile(remoteFile);
  5094. }
  5095. }
  5096. }
  5097. }
  5098. [TestMethod]
  5099. public void Sftp_Open_Truncate_Write_FileDoesNotExist()
  5100. {
  5101. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  5102. {
  5103. client.Connect();
  5104. var remoteFile = GenerateUniqueRemoteFileName();
  5105. if (client.Exists(remoteFile))
  5106. {
  5107. client.DeleteFile(remoteFile);
  5108. }
  5109. try
  5110. {
  5111. Stream stream = null;
  5112. try
  5113. {
  5114. stream = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write);
  5115. Assert.Fail();
  5116. }
  5117. catch (SshException)
  5118. {
  5119. }
  5120. Assert.IsFalse(client.Exists(remoteFile));
  5121. }
  5122. finally
  5123. {
  5124. if (client.Exists(remoteFile))
  5125. {
  5126. client.DeleteFile(remoteFile);
  5127. }
  5128. }
  5129. }
  5130. }
  5131. [TestMethod]
  5132. public void Sftp_OpenRead()
  5133. {
  5134. const int fileSize = 5 * 1024 * 1024;
  5135. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  5136. {
  5137. client.Connect();
  5138. var remoteFile = GenerateUniqueRemoteFileName();
  5139. SftpCreateRemoteFile(client, remoteFile, fileSize);
  5140. try
  5141. {
  5142. using (var s = client.OpenRead(remoteFile))
  5143. {
  5144. var buffer = new byte[s.Length];
  5145. var stopwatch = new Stopwatch();
  5146. stopwatch.Start();
  5147. var bytesRead = s.Read(buffer, offset: 0, buffer.Length);
  5148. stopwatch.Stop();
  5149. var transferSpeed = CalculateTransferSpeed(bytesRead, stopwatch.ElapsedMilliseconds);
  5150. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  5151. Console.WriteLine(@"Transfer speed: {0:N2} KB/s", transferSpeed);
  5152. Assert.AreEqual(fileSize, bytesRead);
  5153. }
  5154. }
  5155. finally
  5156. {
  5157. if (client.Exists(remoteFile))
  5158. {
  5159. client.DeleteFile(remoteFile);
  5160. }
  5161. }
  5162. }
  5163. }
  5164. [TestMethod]
  5165. public void Sftp_SetLastAccessTime()
  5166. {
  5167. var testFilePath = "/home/sshnet/test-file.txt";
  5168. var testContent = "File";
  5169. using var client = new SftpClient(_connectionInfoFactory.Create());
  5170. client.Connect();
  5171. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5172. client.UploadFile(fileStream, testFilePath);
  5173. try
  5174. {
  5175. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  5176. client.SetLastAccessTime(testFilePath, newTime);
  5177. var time = client.GetLastAccessTime(testFilePath);
  5178. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5179. }
  5180. finally
  5181. {
  5182. client.DeleteFile(testFilePath);
  5183. }
  5184. }
  5185. [TestMethod]
  5186. public void Sftp_SetLastAccessTimeUtc()
  5187. {
  5188. var testFilePath = "/home/sshnet/test-file.txt";
  5189. var testContent = "File";
  5190. using var client = new SftpClient(_connectionInfoFactory.Create());
  5191. client.Connect();
  5192. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5193. client.UploadFile(fileStream, testFilePath);
  5194. try
  5195. {
  5196. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5197. client.SetLastAccessTimeUtc(testFilePath, newTime);
  5198. var time = client.GetLastAccessTimeUtc(testFilePath);
  5199. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5200. }
  5201. finally
  5202. {
  5203. client.DeleteFile(testFilePath);
  5204. }
  5205. }
  5206. [TestMethod]
  5207. public void Sftp_SetLastWriteTime()
  5208. {
  5209. var testFilePath = "/home/sshnet/test-file.txt";
  5210. var testContent = "File";
  5211. using var client = new SftpClient(_connectionInfoFactory.Create());
  5212. client.Connect();
  5213. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5214. client.UploadFile(fileStream, testFilePath);
  5215. try
  5216. {
  5217. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  5218. client.SetLastWriteTime(testFilePath, newTime);
  5219. var time = client.GetLastWriteTime(testFilePath);
  5220. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5221. }
  5222. finally
  5223. {
  5224. client.DeleteFile(testFilePath);
  5225. }
  5226. }
  5227. [TestMethod]
  5228. public void Sftp_SetLastWriteTimeUtc()
  5229. {
  5230. var testFilePath = "/home/sshnet/test-file.txt";
  5231. var testContent = "File";
  5232. using var client = new SftpClient(_connectionInfoFactory.Create());
  5233. client.Connect();
  5234. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5235. client.UploadFile(fileStream, testFilePath);
  5236. try
  5237. {
  5238. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5239. client.SetLastWriteTimeUtc(testFilePath, newTime);
  5240. var time = client.GetLastWriteTimeUtc(testFilePath);
  5241. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5242. }
  5243. finally
  5244. {
  5245. client.DeleteFile(testFilePath);
  5246. }
  5247. }
  5248. private static IEnumerable<object[]> GetSftpUploadFileFileStreamData()
  5249. {
  5250. yield return new object[] { 0 };
  5251. yield return new object[] { 5 * 1024 * 1024 };
  5252. }
  5253. private static Encoding GetRandomEncoding()
  5254. {
  5255. var random = new Random().Next(1, 3);
  5256. switch (random)
  5257. {
  5258. case 1:
  5259. return Encoding.Unicode;
  5260. case 2:
  5261. return Encoding.UTF8;
  5262. case 3:
  5263. return Encoding.UTF32;
  5264. default:
  5265. throw new NotImplementedException();
  5266. }
  5267. }
  5268. private static byte[] GetBytesWithPreamble(string text, Encoding encoding)
  5269. {
  5270. var preamble = encoding.GetPreamble();
  5271. var textBytes = encoding.GetBytes(text);
  5272. if (preamble.Length != 0)
  5273. {
  5274. var textAndPreambleBytes = new byte[preamble.Length + textBytes.Length];
  5275. Buffer.BlockCopy(preamble, srcOffset: 0, textAndPreambleBytes, dstOffset: 0, preamble.Length);
  5276. Buffer.BlockCopy(textBytes, srcOffset: 0, textAndPreambleBytes, preamble.Length, textBytes.Length);
  5277. return textAndPreambleBytes;
  5278. }
  5279. return textBytes;
  5280. }
  5281. private static decimal CalculateTransferSpeed(long length, long elapsedMilliseconds)
  5282. {
  5283. return (length / 1024m) / (elapsedMilliseconds / 1000m);
  5284. }
  5285. private static void SftpCreateRemoteFile(SftpClient client, string remoteFile, int size)
  5286. {
  5287. var file = CreateTempFile(size);
  5288. try
  5289. {
  5290. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  5291. {
  5292. client.UploadFile(fs, remoteFile);
  5293. }
  5294. }
  5295. finally
  5296. {
  5297. File.Delete(file);
  5298. }
  5299. }
  5300. private static byte[] GenerateRandom(int size)
  5301. {
  5302. var random = new Random();
  5303. var randomContent = new byte[size];
  5304. random.NextBytes(randomContent);
  5305. return randomContent;
  5306. }
  5307. private static Stream CreateStreamWithContent(string content)
  5308. {
  5309. var memoryStream = new MemoryStream();
  5310. var sw = new StreamWriter(memoryStream, Encoding.ASCII, 1024);
  5311. sw.Write(content);
  5312. sw.Flush();
  5313. memoryStream.Position = 0;
  5314. return memoryStream;
  5315. }
  5316. private static string GenerateUniqueRemoteFileName()
  5317. {
  5318. return $"/home/sshnet/{Guid.NewGuid():D}";
  5319. }
  5320. }
  5321. }