SftpTests.cs 226 KB

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