SftpTests.cs 229 KB

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