SftpTests.cs 225 KB

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