SftpTests.cs 227 KB

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